在很多项目中,有时候我们有阅读一个库的源码的需求。如果在当前工程目录下阅读node_module下的代码,难度无疑会增加,这时候npm link就是最好的办法。它可以将工作目录外的库连接起来,从而替换本地的库
步骤
- 进入目标库目录,执行
npm link,全局注册依赖 - 进入本地工作目录,执行
npm link @package
踩坑
- 本地工作目录可以正常打断点,但是npm link 进来的包打断点无效 排查步骤
- 查看本地工作目录的node_modules,检查是否连接成功
- 清除npm,yarn缓存,浏览器network禁用缓存
- 检查sorceMap有无生成sourceMap,大部分情况下都是源码映射的问题,即vscode得源码和运行得源码没有匹配上
- 如果目标库没有sourceMap,需要对应上正确得运行项目地址,可以查看下面得配置,然后配置别名alias。
vscode配置
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}",
"pathMapping": {
"/@fs/D:/": "D:/",
"/@fs/": "/"
},
"skipFiles": [],
"sourceMaps": true,
}
]
}