前端工程化

webpack Source Map

2021-06-24  本文已影响0人  浅忆_0810

1. 各模式对比

devtool build rebuild production quailty
(none) fastest fastest yes bundled code
eval fastest fastest no generated code
cheap-eval-source-map fast faster no transformed code (lines only)
cheap-module-eval-source-map slow faster no original source (lines only)
eval-source-map slowest fast no original source
cheap-source-map fast slow yes transformed code (lines only)
cheap-module-source-map slow slower yes original source (lines only)
inline-cheap-source-map fast slow no transformed code (lines only)
inline-cheap-module-source-map slow slower no original source (lines only)
source-map slowest slowest yes original source
inline-source-map slowest slowest no original source
hidden-source-map slowest slowest yes original source
nosources-source-map slowest slowest yes without source content

2. webpack配置不同 source-map

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')

const allModes = [
  'eval',
  'cheap-eval-source-map',
  'cheap-module-eval-source-map',
  'eval-source-map',
  'cheap-source-map',
  'cheap-module-source-map',
  'inline-cheap-source-map',
  'inline-cheap-module-source-map',
  'source-map',
  'inline-source-map',
  'hidden-source-map',
  'nosources-source-map'
]

module.exports = allModes.map(item => {
  return {
    devtool: item,
    mode: 'none',
    entry: './src/main.js',
    output: {
      filename: `js/${item}.js`
    },
    module: {
      rules: [{
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }]
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: `${item}.html`
      })
    ]
  }
})
// src/main.js
const element = document.createElement('h2')
element.textContent = 'Hello world'
element.addEventListener('click', () => {
  alert('Hello webpack')
})

document.body.append(heading)

console.log111('main.js running')
# 1. 运行打包命令
npm run build
# 2. 运行 serve
serve dist
浏览器运行结果

3. 不同devtool之间的差异

3.1 eval

没有生成source-map,只能定位源代码文件的名称,不知道具体的行列信息

3.2 eval-source-map

生成了source-map,可以定位到具体的行列信息

3.3 cheap-eval-source-map

只能定位到行,不能定位列

3.4 cheap-module-eval-source-map

只能定位到行,不能定位列,不经过loader加工,和手写代码一样的源代码

总结:


3. 选择合适的source map

3.1 开发环境:cheap-module-eval-source-map

原因:

3.2 生产模式:none

原因:

3.2.1 如果对代码没有信心,可以使用nosources-source-map
上一篇下一篇

猜你喜欢

热点阅读