webpack 源码调试
安装webpack/webpack-cli
javascript
"devDependencies": {
"webpack": "^5.33.2",
"webpack-cli": "^4.6.0"
}
添加inspect
找到node_modules/.bin/
目录,分别在webpack.js
和webpack-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
控制台:
会出现node
的logo
,点击该logo
,即可开始打断点调试:
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
中调试了:
小技巧
调试文档
debug: https://webpack.docschina.org/contribute/debugging/ setup: https://github.com/webpack/webpack/blob/main/_SETUP.md
webpack/examples/
目录下有各种功能的demo
,通过yarn & yarn link & yarn link webpack
建立软连接,然后再/examples/xxxx
目录下运行webpack
即可测试相关功能。