webpack篇,一:webpack 5 热更新体验

工作之余,想自己配一把webpack。热更新卡了半天,直接上代码(标红部分是重点):

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

/*
* 快速生成webpack配置文件:npx webpack-cli init
* 具体配置:https://webpack.docschina.org/configuration/
* */
module.exports = {
  /*
  * "production" | "development" | "none":none默认就是production
  *  根据环境打包,需要将配置导出为函数。
  *  详情:https://webpack.docschina.org/configuration/mode/
  *  module.exports = (env, argv) => {}
  * */
  // context: __dirname, // string(绝对路径!)
  // mode: "development",
  target: "web",  // 这里很重要,默认是package.json中的browserslist,没有的话值是"web"
  entry: {
    // print: "./src/js/print.js",
    index: "./src/index.js",
  }, // String / Object / Array
  devtool: 'inline-source-map', // 帮助发现错误
  output: {
    filename: "[name].bundle.js", // 输出文件名称
    // clean: true, // 每次build清理dist目录
    path: path.resolve(__dirname, 'dist'), // 输出文件目录
    // publicPath: "./", // 静态文件目录,url对应index.html
    // library: { // 这里有一种旧的语法形式可以使用(点击显示)
    //   type: "umd", // 通用模块定义
    //   name: "MyLibrary", // string | string[]
    // },
    // uniqueName: "my-application",
    // name: "my-config",
  },
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    hot: true,
    open: true,
    // hotOnly: true,
    // inline: true,
    proxy: {} // 代理
  },
  module: {
    // rules: [
    //   {
    //     test: /\.less$/i,
    //     use: ["style-loader", "css-loader", "less-loader"],
    //   },
    //   {
    //     test: /\.css$/i,
    //     use: ["style-loader", "css-loader"]
    //   },
    //   {
    //     test: /\.(png|svg|jpg|jpeg|gif)$/i,
    //     type: 'asset/resource',
    //   },
    // ],
  },
  resolve: {},
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: "Development",
      cache: false
    }),
    new webpack.HotModuleReplacementPlugin()
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        extractComments: false // 注释是否提取到单独文件中
      })
    ]
  },
  node: {}
}

记录进步每一天。