Skip to content

webpack 源码调试

安装webpack/webpack-cli

javascript
"devDependencies": {
  "webpack": "^5.33.2",
  "webpack-cli": "^4.6.0"
}

添加inspect

找到node_modules/.bin/目录,分别在webpack.jswebpack-cli.js文件的首行后面添加--inspect-brk

javascript
// 添加前
#!/usr/bin/env node
// 添加后
#!/usr/bin/env node --inspect-brk

运行webpack

定义webpack.config.js文件 ,然后在package.json中定义打包命令:

javascript
"scripts": {
  "build": "webpack"
},

运行npm run build进行打包,命令窗口会出现以下内容:

javascript
Debugger listening on ws://127.0.0.1:9229/8d04b555-653d-45b0-9d19-00f63aed08b1
For help, see: https://nodejs.org/en/docs/inspector

chrome调试

访问ws://127.0.0.1:9229/8d04b555-653d-45b0-9d19-00f63aed08b1网址并打开chrome控制台:

img

会出现nodelogo,点击该logo,即可开始打断点调试:

img

vscode调试

如果想在vscode中调试,手写需要按chrome调试的方法完整操作一遍。然后在vscode中下载chrome调试插件:Debugger for Chrome。下载完成后点击插件提供的运行按钮,选择node环境。在.vscode/目录下会生成一个launch.json文件,将文件替换成一下内容:

javascript
{
  "version": "0.2.0",
    "configurations": [
      {
        "type": "pwa-node",
        "request": "launch",
        "name": "Debug webpack",
        "skipFiles": [
          "<node_internals>/**"
        ],
        "program": "${workspaceFolder}/index.js"
      }
    ]
}

最终就可以在vscode中调试了: img

小技巧

  • webpack/examples/ 目录下有各种功能的 demo,通过 yarn & yarn link & yarn link webpack 建立软连接,然后再 /examples/xxxx 目录下运行 webpack 即可测试相关功能。

参考文章