Webpack能否获取Babel处理后、压缩前的Source Map?
如何在Chrome中查看Babel转译后、压缩前的Webpack构建代码
当然可以实现!你需要调整Webpack和Babel的Source Map配置,让Chrome能识别并展示Babel转译后但还没被压缩的中间代码版本。下面是针对Webpack 4 + babel-loader 8的具体配置步骤:
1. 让Babel生成中间阶段的Source Map
首先在Webpack配置中,给babel-loader添加sourceMap: true选项,让Babel在转译代码时输出自己的Source Map,这样Webpack才能捕捉到转译后的代码与原始代码的映射关系:
// webpack.config.js module.exports = { // ...其他配置 module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], // 你的Babel预设 sourceMap: true // 关键:开启Babel的Source Map生成 } } } ] } };
2. 配置Webpack的Source Map类型
接下来设置Webpack的devtool选项,选择能保留中间转译步骤的Source Map类型:
- 开发环境:推荐使用
eval-cheap-module-source-map,它在保证构建速度的同时,能清晰展示中间代码 - 生产环境:使用
source-map,会生成独立的.map文件,适合线上调试
配置示例:
// webpack.config.js module.exports = { // ...其他配置 devtool: process.env.NODE_ENV === 'production' ? 'source-map' : 'eval-cheap-module-source-map' };
3. 确保压缩工具保留Source Map关联
Webpack 4生产环境默认使用TerserPlugin压缩代码,需要开启它的sourceMap选项,否则压缩时会丢失中间的Source Map信息:
// webpack.config.js const TerserPlugin = require('terser-webpack-plugin'); module.exports = { // ...其他配置 optimization: { minimizer: [ new TerserPlugin({ sourceMap: true // 确保压缩时保留Source Map映射 }) ] } };
如何在Chrome中找到转译后的代码
配置完成并重新构建后,打开Chrome的Sources面板:
- 展开左侧的
webpack://目录 - 找到带有
babel-loader前缀的文件(格式类似./node_modules/babel-loader/lib/index.js!./src/your-file.js) - 点击打开这个文件,就是Babel转译后、压缩前的代码了
你仍然可以在同一目录下找到原始的src/your-file.js,方便随时对比转译前后的代码差异。
内容的提问来源于stack exchange,提问作者Rickard Liljeberg
相关产品推荐
相关产品推荐

