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()
    //]
});
posted @ 2021-04-09 13:51  是明啊  阅读(1672)  评论(0编辑  收藏  举报