webpack5.x配置示例


package.json

{
  "name": "my-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack serve --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.10",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/plugin-transform-runtime": "^7.13.10",
    "@babel/preset-env": "^7.13.10",
    "@babel/runtime": "^7.13.10",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^5.1.3",
    "csv-loader": "^3.0.3",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.1",
    "mini-css-extract-plugin": "^1.3.9",
    "node-sass": "^5.0.0",
    "optimize-css-assets-webpack-plugin": "^5.0.4",
    "sass-loader": "^11.0.1",
    "style-loader": "^2.0.0",
    "terser-webpack-plugin": "^5.1.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.27.1",
    "webpack-cli": "^4.5.0",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.7.3",
    "xml-loader": "^1.2.1"
  },
  "dependencies": {
    "jquery": "^3.6.0"
  }
}

webpack.common.js(公共配置,dev/prod環境都會用的配置,可用npm下載webpack-merge進行配置文件合並)

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    entry: './src/index.js',  // 入口文件
    output: {
        filename: '[name].[chunkhash].bundle.js',  // 定義輸出文件名
        path: path.resolve(__dirname, 'dist')    // 定義輸出文件夾dist路徑
    },
    plugins: [
        new CleanWebpackPlugin({  // 每次打包前刪除dist文件夾中的文件
            cleanOnceBeforeBuildPatterns: ['**/*', '!favicon.ico', '!lib/**'],//dist文件夾下的favicon.ico文件和lib文件夾下的東西都忽略不進行刪除
        }),
        new HtmlWebpackPlugin({
            // title: 'index'  //如果項目沒有html文件作為模板入口,可使用title和filename進行自動創建,這里使用模板
            // filename: 'index.html',
            template: 'index.html', //指定html模板文件
            favicon: 'favicon.ico', //指定網站圖標
            inject: 'head' //js插入的位置,插入head中也會自動補defer="defer"屬性以保證在頁面加載后執行js,如果考慮兼容性可改成body
            // minify: {
            //     removeAttributeQuotes: true // 可移除屬性的引號
            // }
        }),
        new MiniCssExtractPlugin({ //css獨立打包
            filename: "[name]-[contenthash].css"
        }),
        new Webpack.ProvidePlugin({ //全局引入jquery,此后在任何位置可直接使用$,Lodash或其他庫也可以像這樣引入,當然也可以在dist目錄的lib文件夾下放第三方庫,在html模板中直接引入
            '$':'jquery'
        })
    ],
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"  //es6+轉換es5
                }
            },
            {
                test: /\.s[ac]ss$/,  //sass/scss轉換css
                use: [MiniCssExtractPlugin.loader,'css-loader','sass-loader']
            },
            {
                test: /\.(png|svg|jpg|gif|webp|jfif)$/, //圖片打包
                use: [
                    {
                        loader: "url-loader",  //圖片base64化
                        options: {
                            limit: 1024 * 100,  //小於100kb的圖片會被base64
                            name: "assets/[name]_[hash:10].[ext]"
                        }
                    }
                ]
            },
            {
                test: /\.(csv|tsv)$/, //CSV/TSV文件打包
                use: [
                    'csv-loader',
                ],
            },
            {
                test: /\.xml$/, //XML文件打包
                use: [
                    'xml-loader',
                ],
            },
        ]
    }
};

webpack.prod.js(生產環境配置)

const { merge } = require('webpack-merge'); //引入配置文件合並工具
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserJSPlugin = require("terser-webpack-plugin");
const common = require('./webpack.common.js'); //引入公共配置

module.exports = merge(common, {
    mode: "production",
    optimization: {
        minimizer: [new OptimizeCSSAssetsPlugin({})],//css壓縮混稀
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})]//js壓縮混稀
    }
});

webpack.dev.js(開發環境配置)

const { merge } = require('webpack-merge');
const path = require('path');
const common = require('./webpack.common.js');
// const webpack = require('webpack');

module.exports = merge(common, {
    mode: 'development',
    devtool: "inline-source-map", //控制台提示信息映射
    devServer: { //開發服務器
        contentBase: path.resolve(__dirname, "dist"),
        port: "8090",
        proxy: { //反向代理,根據需求自行修改
            "/api": {
                target: "http://127.0.0.1:3001",
                pathRewrite: {
                    "^/api": ""
                  }
            },
            "/resource": {
                target: "http://127.0.0.1:3002",
                pathRewrite: {
                  "^/resource": ""
                }
            }
        },
        open: true,  //自動打開瀏覽器
        // hot: true, //讓webpackDevServer開啟熱更新功能
        // hotOnly: true //當hot module replacement功能沒生效時,也不允許瀏覽器重新加載
    },
    //如需熱更新,開啟下面代碼
    //plugins: [
    //    new webpack.HotModuleReplacementPlugin()
    //]
});


免責聲明!

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



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