在线上环境中,由于项目代码都被打包到了一个文件中,难以调试和定位。此时可以通过source map来实现项目代码的定位和调试。
一般开发环境中默认source map打开,但线上环境必须关闭
一、 为什么要使用 source map
没有source map时:
使用了source map时:
可以明显看到,调试时显示的是真实代码
二、关键字
- eval: 使用eval包裹模块代码,包裹后的模块打包后,会产生相对应的source map 文件
- source map: 产生.map文件
- cheap: 不包含列信息,即不会暴露到第几列,只能暴露到行
- inline: 将.map作为DataURI嵌入,不单独生成.map文件
- module: 包含loader的sourcemap
三、类型分类
四、安装和配置
github项目地址:webpack样例
使用 devtool 关键字开启source-map调试
'use strict';
const path = require('path')
const webpack = require('webpack');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const glob = require('glob');
const setMPA = () => {
const entry = {};
const htmlWebpackPlugins = [];
const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));
Object.keys(entryFiles)
.map((index) => {
const entryFile = entryFiles[index];
// '/Users/cpselvis/my-project/src/index/index.js'
const match = entryFile.match(/src\/(.*)\/index\.js/);
const pageName = match && match[1];
entry[pageName] = entryFile;
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
inlineSource: '.css$',
template: path.join(__dirname, `src/${pageName}/index.html`),
filename: `${pageName}.html`,
chunks: ['vendors', pageName],
inject: true,
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
})
);
});
return {
entry,
htmlWebpackPlugins
}
}
const { entry, htmlWebpackPlugins } = setMPA();
module.exports = {
entry: entry,
output: {
filename: '[name].js',
path: path.join(__dirname, 'dist'),
},
mode: 'development',
module: {
....
},
plugins: [
....
].concat(htmlWebpackPlugins),
devtool: 'source-map', // 开启source-map调试
devServer: {
contentBase: './dist',
hot: true
}
}