Webpackage 5 has been released for a period of time, but vue-CLI still has WebPackage 4. As a result, the new functions of WebPackage 5 cannot be used, especially tree shaking and caching

Project directory structure

SRC ├─ Assets ├─ Style ├─ Public Functions ├─ views.Vue ├─ index.html Template ├─ Index.js (entry file)Copy the code

Set up steps

  1. Setting up basic Configurations

    1. Add entry, exit configuration
    const { resolve } = require("path")
    module.exports = {
        entry: resolve(__dirname, 'src/index.js'),
        output: {
            filename: '[name][contenthash:8].js'.path: resolve(__dirname, 'dist'),
            clean: true,}}Copy the code
    1. Add HTML template parsing
    const { resolve } = require("path")
    module.exports = {
        plugins: [new HtmlWebpackPlugin({
             template: resolve(__dirname, 'src/index.html'),
             //<title><%=htmlWebpackPlugin.options.title %></title>
             // Notice that htmlWebpackPlugin starts with a lowercase letter
             title: "webpack5-vue"]}}),Copy the code
    1. Adding resource resolution
    module.exports = {
     module: {
         rules: [
             /** Webpack5 incorporates the resource module, which automatically processes resource files such as images, fonts, etc., * so there is no need to use loader */
             {
                 test: /\.(jpe? g|png|gif|svg)$/i,
                 type: 'asset'.parser: {
                     dataUrlCondition: {
                         maxSize: 4 * 1024 // 4kb}},generator: {
                     // Change the build path separately
                     filename: 'img/[hash:8][ext][query]'}}, {test: /\.(ttf|woff2)$/i,
                 type: 'asset'.generator: {
                     // Change the build path separately
                     filename: 'font/[hash:8][ext][query]'}},]},}Copy the code
    1. Add Reference resolution
    const { resolve } = require("path")
    module.exports = {
        resolve: {
         alias: {
             The '@': resolve(__dirname, 'src'),}}}Copy the code
    1. Add the vue – loader
    const { VueLoaderPlugin } = require('vue-loader')
    module.exports = {
    module: {
         rules: [{test: /\.vue$/i,
                 loader: 'vue-loader']}},plugins: [new VueLoaderPlugin(),
        ]
    }
    Copy the code
  2. Setting up the development environment

const { resolve } = require("path")
const { merge } = require("webpack-merge")
const base = require("./webpack.base")
const cssLoader = ['vue-style-loader'.'css-loader']
// Merge the base configuration using webpack-merge
module.exports =  merge(base,{
    mode: "development".module: {
        rules: [{test: /\.css$/i,
                use: cssLoader,
            },
            {
                test: /\.scss$/i,
                use: [...cssLoader, 'sass-loader'] {},test: /\.(js|vue)$/i.// Add esLint checks
                enforce: 'pre'.// Enforce priority permission to prevent conflicts with Babel
                exclude: /node_modules/,
                loader: 'eslint-loader'.// For the eslint-loader configuration, see the rear.eslintrc.js file
                options: {
                    fix: true// Custom fixes syntax errors}}},],devtool: 'eval-cheap-module-source-map'.devServer: {
        compress: true.static: {
            directory: resolve(__dirname, 'dist'),},liveReload: true.// Enable hot updates
    },
    target: "web".// Enable hot update target:"web"
    cache: true.resolve: {
        alias: {
            // When parsing import Vue from 'Vue', find the path of Vue
            vue$: resolve(__dirname, 'node_modules/vue/dist/vue.esm.js'),}}})Copy the code
  1. Setting up the release environment
const { resolve } = require("path")
const { merge } = require("webpack-merge")
const base = require("./webpack.base")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

const cssLoader = [MiniCssExtractPlugin.loader, 'css-loader', {
    loader: 'postcss-loader'.// CSS automatic compatibility
    options: {
        postcssOptions: {
            plugins: [['postcss-preset-env',
                    {
                        // Other options},],]}}}]module.exports = merge(base, {
    mode: "production".output: {
        environment: {
            // Do not use arrow mode, compatible with IE9
            arrowFunction: false
        },
        // Modify the resource generation path
        assetModuleFilename: 'assets/[hash:8][ext][query]',},module: {
        rules: [{test: /\.js$/i,
                exclude: /node_modules/,
                use: [{
                    loader: 'babel-loader'.* "browserslist": ["> 1%", "last 2 versions", "not IE <= 8"] */
                    // You can separate the configuration from the. Babelrc file
                    options: {
                        cacheDirectory: true.presets: [["@babel/preset-env",
                                {
                                    modules: false.useBuiltIns: "usage".corejs: 3}]}}],}, {test: /\.css$/i,
                use: cssLoader,
            },
            {
                test: /\.scss$/i,
                use: [...cssLoader, 'sass-loader']},]},// devtool:'none',
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style/[name][contenthash:8].css'}),].resolve: {
        alias: {
            vue$: resolve(__dirname, 'node_modules/vue/dist/vue.min.js')}},optimization: {
        //sideEffects:true to be used with the sideEffect field of package.json,
        // The package.json sideEffect configuration is as follows: true All code has side effects (do not delete), false (all can be deleted), arrays (do not delete those files)
        // When sideEffects is enabled, styles are removed.
        //1. We can use require to dynamically introduce CSS styles to avoid being shaken off by tree shaking. require('./style.css')
        //2. Do not tree shaking CSS files, add array [" *.css "] in package.json, do not tree shaking CSS files. [recommend]
        sideEffects: true.// Tree shaking Commonjs is also supported
        // minimize:true,
        minimizer: [
            `... `.// Leave the default Settings, otherwise js will not be compressed
            new CssMinimizerPlugin(),/ / compress CSS].splitChunks: {// Chunk cutting, extract common code, reduce the main package size
            // include all types of chunks
            chunks: 'all'.cacheGroups: {
                vue: {
                    name: 'chunk-vue'.test: /[\\/]node_modules[\\/](vue|vuex|vue-router)[\\/]/,
                    chunks: 'all'.priority: -10
                },
                elementUi: {
                    name: 'chunk-element-ui'.test: /[\\/]node_modules[\\/]element-ui[\\/]/,
                    chunks: 'all'.priority: -9}}},},})Copy the code
  1. . Eslintrc. Js configuration

    1. Run the NPX eslint –init command to generate the. Eslintrc. js configuration, select support vuejs, select Node to automatically generate the configuration file

module.exports = {
    "env": {
        "es2021": true."node": true
    },
    "extends": [
        "eslint:recommended"."plugin:vue/essential",]."parserOptions": {
        "ecmaVersion": 12."sourceType": "module"
    },
    "plugins": [
        "vue"]};Copy the code

2. Add the eslint-config-Airbnb-BAS rule

"extends": [
        "eslint:recommended"."plugin:vue/essential"."airbnb-base"].Copy the code

3. Add your own rules

    "rules": {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off".'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.'import/no-unresolved': [
            'off',
            {
                ignore: ['^ @ /'].// @ is the path alias},]."semi": ["error"."never"]./ / a semicolon
        "quotes": ["error"."single"].// String ""
    }
Copy the code