xccjk / x-blog

学习笔记
18 stars 2 forks source link

webpack模块热更新? #14

Closed xccjk closed 2 years ago

xccjk commented 4 years ago

webpack热更新

什么是浏览器的热更新

手动模式

  // 1.js
  console.log(a)
  // webpack.config.basic.js
  module.exports = {
    entry: './src/1.js',
    mode: 'development'
  }
  // package.json
  script: {
    ...
    "build:basic": "webpack --config webpack.config.basic.js"
  }

watch

  // webpack.config.watch.js
  module.exports = {
    entry: './src/1.js',
    mode: 'development',
    watch: true
  }
  // package.json
  "build:watch": "webpack --config webpack.config.watch.js"

Live Reload

  // webpack.config.reload.js
  module.exports = {
    entry: './src/1.js',
    mode: 'development',
    watch: true,
    devServer: {
      // 为dist下静态文件提供本地服务渲染
      contentBase: './dist',
      open: true
    }
  }
  // package.json
  script: {
    ...
    "dev:reload": "webpack-dev-server --config webpack.config.reload.js"
  }

原理

问题

Hot Module Replacement - 模块热替换

  // 1.js
  import './style.css'
  ...
  // style.css
  div {
    color: red
  }
  // webpack.config.hmr.js
  // 添加devServer hot与css解析器style-loader与css-loader
  module.exports = {
    entry: './src/index-0.js',
    mode: 'none',
    watch: true,
    devServer: {
      // 为dist下静态文件提供本地服务渲染
      contentBase: './dist',
      open: true,
      hot: true
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader']
        }
      ]
    }
  }
  package.json
  script: {
    ...
    "dev:hmr": "webpack-dev-server --config webpack.config.hmr.js"
  }

问题

  1. 为什么修改js不能模拟出热替换的效果?

webpack热更新原理

webpack的打包流程

打包思想