zoukankan      html  css  js  c++  java
  • 654 webpack的Terser、CSS的压缩

    Terser介绍和安装


    命令行使用Terser


    Compress和Mangle的options


    Terser在webpack中配置


    CSS的压缩


    index.js

    import {sum, mul} from "./math";
    
    import _ from "lodash";
    
    console.log(sum(20, 30));
    console.log(mul(20, 30));
    

    main.js

    import "./style.css";
    
    const message = "Hello World";
    console.log(message);
    
    function sum(num1, num2) {
      return arguments[0] + arguments[1];
    }
    
    console.log(sum(20, 30));
    
    const info = {
      foo() {
        return "foo"
      }
    }
    
    if (false) {
      console.log("哈哈哈");
    }
    
    class Person {}
    
    console.log(new Person());
    

    webpack.common.js

    const resolveApp = require("./paths");
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const VueLoaderPlugin = require("vue-loader/lib/plugin");
    const TerserPlugin = require("terser-webpack-plugin");
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const webpack = require('webpack');
    
    const { merge } = require("webpack-merge");
    
    const prodConfig = require("./webpack.prod");
    const devConfig = require("./webpack.dev");
    
    const commonConfig = (isProduction) => {
      return {
        entry: {
          main: "./src/main.js",
          index: "./src/index.js"
          // main: { import: "./src/main.js", dependOn: "shared" },
          // index: { import: "./src/index.js", dependOn: "shared" },
          // lodash: "lodash",
          // dayjs: "dayjs"
          // shared: ["lodash", "dayjs"]
        },
        output: {
          path: resolveApp("./build"),
          filename: "js/[name].[chunkhash:6].bundle.js",
          chunkFilename: "js/[name].[contenthash:6].chunk.js",
          publicPath: ""
        },
        resolve: {
          extensions: [".wasm", ".mjs", ".js", ".json", ".jsx", ".ts", ".vue"],
          alias: {
            "@": resolveApp("./src"),
            pages: resolveApp("./src/pages"),
          },
        },
        optimization: {
          // 对代码进行压缩相关的操作
          // natural: 使用自然数(不推荐),
          // named: 使用包所在目录作为name(在开发环境推荐)
          // deterministic: 生成id, 针对相同文件生成的id是不变
          // chunkIds: "deterministic",
          splitChunks: {
            // async异步导入
            // initial同步导入
            // all 异步/同步导入
            chunks: "all",
            // 最小尺寸: 如果拆分出来一个, 那么拆分出来的这个包的大小最小为minSize
            minSize: 20000,
            // 将大于maxSize的包, 拆分成不小于minSize的包
            maxSize: 20000,
            // minChunks表示引入的包, 至少被导入了几次
            minChunks: 1,
            cacheGroups: {
              vendor: {
                test: /[\/]node_modules[\/]/,
                filename: "js/[id]_vendors.js",
                // name: "vendor-chunks.js",
                priority: -10
              },
              // bar: {
              //   test: /bar_/,
              //   filename: "[id]_bar.js"
              // }
              default: {
                minChunks: 2,
                filename: "common_[id].js",
                priority: -20
              }
            }
          },
          // true/multiple
          // single
          // object: name
          // runtimeChunk: {
          //   name: function(entrypoint) {
          //     return `why-${entrypoint.name}`
          //   }
          // }
        },
        module: {
          rules: [
            {
              test: /.jsx?$/i,
              use: "babel-loader",
            },
            {
              test: /.vue$/i,
              use: "vue-loader",
            },
            {
              test: /.css/i,
              // style-lodader -> development
              use: [
                isProduction ? MiniCssExtractPlugin.loader: "style-loader", 
                "css-loader"],
            },
          ],
        },
        plugins: [
          new HtmlWebpackPlugin({
            template: "./index.html",
          }),
          new VueLoaderPlugin(),
          // 当在代码中遇到某一个变量找不到时, 我们会通过ProvidePlugin, 自动导入对应的库
          // new webpack.ProvidePlugin({
          //   axios: "axios",
          //   get: ["axios", "get"]
          // })
        ],
      };
    }
    
    module.exports = function(env) {
      const isProduction = env.production;
      process.env.NODE_ENV = isProduction ? "production" : "development";
    
      const config = isProduction ? prodConfig : devConfig;
      const mergeConfig = merge(commonConfig(isProduction), config);
    
      return mergeConfig;
    };
    

    webpack.prod.js

    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
    const TerserPlugin = require('terser-webpack-plugin');
    const webpack = require('webpack');
    
    const isProduction = true;
    
    module.exports = {
      mode: "development",
      devtool: "source-map",
      externals: {
        lodash: "_",
        dayjs: "dayjs"
      },
      optimization: {
        minimize: false,
        minimizer: [
          new TerserPlugin({
            parallel: true,
            extractComments: false,
            terserOptions: {
              compress: {
                arguments: false,
                dead_code: true
              },
              mangle: true,
              toplevel: true,
              keep_classnames: true,
              keep_fnames: true
            }
          })
        ]
      },
      plugins: [
        // 生成环境
        new CleanWebpackPlugin({}),
        new MiniCssExtractPlugin({
          filename: "css/[name].[contenthash:6].css"
        }),
        new CssMinimizerPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin()
      ]
    }
    

    webpack.dev.js

    const resolveApp = require('./paths');
    const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
    
    const isProduction = false;
    
    console.log("加载devConfig配置文件");
    
    module.exports = {
      mode: "development",
      devServer: {
        hot: true,
        hotOnly: true,
        compress: true,
        contentBase: resolveApp("./why"),
        watchContentBase: true,
        proxy: {
          "/why": {
            target: "http://localhost:8888",
            pathRewrite: {
              "^/why": ""
            },
            secure: false,
            changeOrigin: true
          }
        },
        historyApiFallback: {
          rewrites: [
            {from: /abc/, to: "/index.html"}
          ]
        }
      },
      plugins: [
        // 开发环境
        new ReactRefreshWebpackPlugin(),
      ]
    }
    

  • 相关阅读:
    什么是基于注解的容器配置?
    一个线程运行时发生异常会怎样?
    Java 中你怎样唤醒一个阻塞的线程?
    为什么 wait, notify 和 notifyAll 这些方法不在 thread 类里面?
    Java 中 notify 和 notifyAll 有什么区别?
    在 Spring MVC 应用程序中使用 WebMvcTest 注释有什么用处?
    java 中有几种方法可以实现一个线程?
    什么是AOP?
    什么是竞争条件?你怎样发现和解决竞争?
    Mybatis 是如何进行分页的?分页插件的原理是什么?
  • 原文地址:https://www.cnblogs.com/jianjie/p/14545893.html
Copyright © 2011-2022 走看看