IT俱乐部 JavaScript 前端代码打包与压缩的完整指南

前端代码打包与压缩的完整指南

一、打包工具选型对比

1.1 主流打包工具特性对比

工具 速度 Tree Shaking 代码分割 热更新 适用场景
Webpack ✔️ ✔️ ✔️ 复杂SPA
Rollup ✔️ ✔️ 库开发
Parcel 最快 ✔️ ✔️ ✔️ 快速原型
esbuild 极快 ✔️ ✔️ ✔️ 大型项目
Vite 超快 ✔️ ✔️ ✔️ 现代框架

1.2 工具选择决策树

二、Webpack 完整配置

2.1 基础生产配置

// webpack.config.prod.js
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: '[name].[contenthash:8].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true,
        terserOptions: {
          compress: {
            drop_console: true,
          },
        },
      }),
      new CssMinimizerPlugin(),
    ],
    splitChunks: {
      chunks: 'all',
    },
  },
};

2.2 高级优化配置

代码分割策略:

optimization: {
  splitChunks: {
    cacheGroups: {
      vendors: {
        test: /[\/]node_modules[\/]/,
        name: 'vendors',
        chunks: 'all',
      },
      commons: {
        name: 'commons',
        minChunks: 2,
        chunks: 'initial',
        minSize: 0,
      },
    },
  },
  runtimeChunk: {
    name: 'runtime',
  },
}

持久化缓存:

module.exports = {
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename],
    },
  },
};

三、代码压缩技术详解

3.1 JavaScript 压缩

Terser 配置选项

new TerserPlugin({
  parallel: 4,  // 使用4个线程
  extractComments: false,  // 不提取注释
  terserOptions: {
    compress: {
      pure_funcs: ['console.info'], // 只移除console.info
      dead_code: true,  // 删除不可达代码
      drop_debugger: true,
    },
    format: {
      comments: false,  // 移除所有注释
    },
    mangle: {
      properties: {
        regex: /^_/,  // 只混淆下划线开头的属性
      },
    },
  },
})

3.2 CSS 压缩优化

PostCSS 配置

// postcss.config.js
module.exports = {
  plugins: [
    require('cssnano')({
      preset: ['advanced', {
        discardComments: { removeAll: true },
        colormin: true,
        zindex: false,
      }]
    }),
    require('autoprefixer')
  ]
}

3.3 HTML 压缩

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        useShortDoctype: true,
        minifyCSS: true,
        minifyJS: true,
      },
    }),
  ],
};

四、高级打包技巧

4.1 按需加载

React 动态导入

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function MyComponent() {
  return (
    Loading...

}>

);
}

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/js/15982.html
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部