JS压缩

  • webpack内置了uglifyjs-webpack-plugin

CSS压缩

  • 使用css-minimizer-webpack-plugin
    • 下载包npm i css-minimizer-webpack-plugin -D
  • 同时使用cssnano

    • css的预处理器
    • 下载包:npm i cssnano -D
      1. // webpack.prod.js
      2. 'use strict';
      3. const path = require('path');
      4. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
      5. const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
      6. module.exports = {
      7. module: {
      8. rules: [
      9. {
      10. test: /\.css$/,
      11. use: [MiniCssExtractPlugin.loader, 'css-loader']
      12. },
      13. {
      14. test: /\.less$/,
      15. use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
      16. },
      17. {
      18. test: /\.(scss|sass)$/,
      19. use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      20. },
      21. },
      22. plugins: [
      23. new MiniCssExtractPlugin({
      24. filename: '[name]_[contenthash:8].css'
      25. }),
      26. new CssMinimizerPlugin(),
      27. ],
      28. mode: 'production',
      29. }

      html压缩

  • 使用html-webpack-plugin,设置压缩参数

    • 下载包:npm i html-webpack-plugin -D
  1. // webpack.config.js
  2. 'use strict';
  3. const path = require('path');
  4. const HtmlWebpackPlugin = require("html-webpack-plugin");
  5. module.exports = {
  6. plugins: [
  7. // 多个html就,写多个HtmlWebpackPlugin,然后把index换成对应的html的名称
  8. new HtmlWebpackPlugin({
  9. template: path.join(__dirname, 'src/index.html'),
  10. filename: 'index.html',
  11. chunk: ['index'],
  12. inject: true,
  13. minify: {
  14. html5: true,
  15. collapseWhitespace: true,
  16. preserveLineBreaks: false,
  17. minifyCSS: true,
  18. minifyJS: true,
  19. removeComments: false
  20. }
  21. })
  22. ],
  23. mode: 'production',
  24. }