一个webpack单页面应用的配置

783 阅读1分钟

主文件webpack.config.js

/**作用域分析treeshaking */
const WebpackDeepScopeAnalysisPlugin = require('webpack-deep-scope-plugin').default;

const path = require('path');
const glob = require('glob');
/*CSS 样式表处理部分的插件 */
// CSS TreeShaking
const PurifyCSSPlugin = require('purifycss-webpack');
//提取css
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// HTML 插件
const HtmlWebpackPlugin = require('html-webpack-plugin')

/**生产 / 开发 环境区分 */
const merge = require("webpack-merge");
//merge() 函数用于合并两个对象或者数组内容到第一个数组。
const argv = require('yargs-parser')(process.argv.slice(2));
//{ _: [], mode: 'production' } 获取全局变量的状态
//没有的话就是开发环境
const _mode = argv.mode || "development";
const _modeFlag = (_mode || "production" ? true : false);
// 引入分支文件中写的内容
const _mergeConfig = require(`./webpack-config/webpack.${_mode}.js`)


//  清空dist文件夹的插件
const CleanWebpackPlugin = require('clean-webpack-plugin');

const webpackConfig = {
    devServer: {
        port: 3000,
        open: true,
        hot: true,//热更新
        before(app) { // 自带默认express的socket
            // 打开http://localhost:3000/api/test : {"code":200,"message":"JsonPlaceHolder"}
            app.get("/api/test", (req, res) => { //假接口
                res.json({
                    code: 200,
                    message: "JsonPlaceHolder"
                })
            })
        }
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    chunks: "initial",
                    name: 'common',
                    minChunks: 1, //最少引用数
                    maxInitialRequests: 5, // 最多引用数 
                    minSize: 0
                }
            }
        },
        runtimeChunk: {
            name: "runtime"
        }
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'
                        }
                    },
                    // {
                    //     loader: 'style-loader'
                    // },
                    {
                        loader: 'css-loader'
                        // loader: 'css-loader?modules' //css模块化解析
                        // loader: 'css-loader?modules&localIdentName=[name]_[local]-[hash:base64:5]' //css模块化解析 index_test-q7KCi
                    }]
            }
        ]
    },
    plugins: [
        new WebpackDeepScopeAnalysisPlugin(),


        new MiniCssExtractPlugin({
            // filename 同步引入css命名
            // chunkFilename 一部引入的css命名 魔法注释引入 style0.[hash:5].css
            filename: _modeFlag ? 'style/[name].[hash:5].css' : 'style/[name].css',
            chunkFilename: _modeFlag ? 'style/style[id].[hash:5].css' : 'style/style[id].css',
        }),

        new HtmlWebpackPlugin({
            filename: 'index.html', // 输出后的文件名
            template: 'src/index.html' // 输出前的源文件
        }),
        // new PurifyCSSPlugin({ 
        //     //脚本中加入的css选择器不会被加入到里面,会被抖动掉,正则匹配
        //     // 生成后的HTML文件的绝对路径
        //     paths: glob.sync(path.join(__dirname, '/dist/*.html')),
        // }),
        new CleanWebpackPlugin(),
    ],
}

//分支文件和主文件合并分支
module.exports = merge(_mergeConfig, webpackConfig);

分支文件

  • 生产模式
module.exports = {
    output: {
        filename: 'scripts/[name].[hash:5].bundle.js',
        publicPath: '/'
    }
}
  • 开发模式
module.exports = {
    output: {
        filename: 'scripts/[name].bundle.js',
        publicPath: '/'
    }
}
  • package.json 文件
{
  "name": "spa",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "dev:server": "webpack-dev-server --mode development",
    "prod": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^2.0.2",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.9.0",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.7.0",
    "purify-css": "^1.2.5",
    "purifycss-webpack": "^0.7.0",
    "style-loader": "^0.23.1",
    "uglifyjs-webpack-plugin": "^2.1.3",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.2",
    "webpack-deep-scope-plugin": "^1.6.0",
    "webpack-dev-server": "^3.4.1",
    "webpack-merge": "^4.2.1",
    "yargs-parser": "^13.1.0"
  },
  "dependencies": {
    "lodash-es": "^4.17.11",
    "mini-css-extract-plugin": "^0.7.0"
  }
}