Debug下查看webpack编译过程

我们知道在浏览器的source面板中可以进行断点调试,但是webpack编译过程是在Nodejs环境中进行的,怎么才能打断点查看编译过程呢?


vscode提供了断点调试功能,包括Chrome和Nodejs,下面介绍一下怎么去配置
1、首先用vscode打开你要调试的项目
2、键盘F5键或者点击菜单(Run->Start Debugging),会出现下图
image.png
然后点击创建一个launch.js文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
// 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": "node", // node环境
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\index.js" // 开始执行的文件
}
]
}

然后检查type对应的环境和program对应的开始执行文件,在你的index.js文件相应的位置打上debugger,再次按F5,就会从index.js开始执行到debugger的地方


下面用webpack编译举个例子
1、创建一个文件夹 webpack-debug , 运行 npm init -y ,然后 npm i webpack -D
2、在根目录下创建一个app.js文件,简单添加点内容
1
2
3
4
// app.js
const app = 'app'

export default app


3、配置webpack.config.js

1
2
3
4
5
6
7
8
module.exports = {
mode: 'none',
entry: './app.js',
output: {
filename: '[name].js',
path: __dirname + '/lib',
}
}

4、添加启动脚本文件start.js
1
2
3
4
5
6
7
8
9
10
11
12
const webpack = require('webpack')
const config = require('./webpack.config')

debugger

const compiler = webpack(config)

debugger

compiler.run(err => {
console.log(err)
})

5、根据前面介绍的添加launch.json文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
// 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": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\start.js" // 从start.js开始启动
}
]
}

6、F5进行调试
image.png


可以使用step into image.png查看每一步调用

本节代码:链接

webpack基本原理可查看这篇:webpack基本原理