开启热更新

开启热更新

从 webpack-dev-server v4 开始,HMR 是默认启用的。它会自动应用 webpack.HotModuleReplacementPlugin,这是启用 HMR 所必需的。

  1. devServer: {
  2. static: {
  3. directory: path.join(__dirname, 'public'),
  4. },
  5. compress: true,
  6. port: 9000,
  7. hot: true,
  8. },

文件内
HotModuleReplacementPlugin会为文件注入 module.hot

  1. import { a } from './hot';
  2. if (module.hot) {
  3. module.hot.accept('./hot', () => {
  4. console.log(a);
  5. });
  6. }

React 热更新

需要下载 react react-dom,热更新需要加载 react-refresh @pmmmwh/react-refresh-webpack-plugin @babel/preset-react
webpack配置

  1. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  2. modules:{
  3. rules:[
  4. {
  5. test: /\.jsx?$/,
  6. use: ['babel-loader'],
  7. },
  8. ]
  9. },
  10. plugins:[
  11. new ReactRefreshWebpackPlugin(),
  12. ]

babel.config,js

  1. module.exports = {
  2. presets: [['@babel/preset-env'], ['@babel/preset-react']],
  3. plugins: [['react-refresh/babel']],
  4. };

vue 热更新

需要下载 vue vue-loader vue-vue-template-compiler
注:vue-loader@14版本直接引用就好

  1. const VueLoaderPlugin = require('vue-loader');

vue-loader@15之后

  1. const VueLoaderPlugin = require('vue-loader/lib/plugin');

webpack

  1. const VueLoaderPlugin = require('vue-loader/lib/plugin');
  2. modules:{
  3. rules:[
  4. {
  5. test: /\.vue$/,
  6. use: ['vue-loader'],
  7. },
  8. ]
  9. },
  10. plugins:[
  11. new VueLoaderPlugin(),
  12. ]