sourcemap:devtool

文章目录
  1. 1. webpack配置
  2. 2. soucemap

webpack配置

参考资料

  • devtool
    • cheap: 映射不到源码对应列
    • module: 包含loader的sourcemap
    • eval: 构建会快一些,但不能用在生产环境
    • source-map: 产生.map文件

开发环境: cheap-module-eval-source-map
生产环境: cheap-module-source-map

生成的sourcemap代码切勿上传到外网,否则会造成源码泄漏;可以配合@sentry/webpack-plugin上传到sentry

const isProduction = process.env.NODE_ENV === 'production';
const devtool = isProduction ? 'source-map' : 'cheap-module-eval-source-map';

module.exports = {
mode: isProduction ? 'production' : 'development',
devtool,
...
}
// package.json
{
...
"scripts": {
"build": "export NODE_ENV=production && webpack",
}
}

soucemap

sourcemap的原理

报错监控结合sourcemap

import { SourceMapConsumer } from 'source-map';

// rawSourceMap是sourcemap文件对象
SourceMapConsumer.with(rawSourceMap, null, consumer => {

console.log(
consumer.generatedPositionFor({
// two.js的第2行,第10列报错
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
})
);
// 输出对应源码的:{ line: 2, column: 28 }

})