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: {}
}

 

記錄進步每一天。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM