Webpack 代码拆分影响 Web 性能

Nic*_*ies 5 javascript bundle reactjs webpack code-splitting

我有一个 React/Node + SSR 应用程序,我正在尝试创建一个生产构建,我已经设法做到了,但问题是我在构建中的文件太大了。我使用最新版本的 react + webpack 4。这是我的 webpack 配置:

客户端配置文件

const path = require('path');
const common = require('./webpack.common-config');

const clientConfig = {
  ...common,
  mode: 'production',
  name: 'client',
  target: 'web',
  devtool: false,
  entry: {
    client: [
      '@babel/polyfill',
      './src/client.js'
    ],
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: '[name].js',
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          chunks: 'all',
          name: 'vendor',
          test: module => /node_modules/.test(module.resource),
          enforce: true
        },
        common: {
          chunks: 'all',
          name: 'client'
        }
      },
    },
  },
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  }
};

module.exports = clientConfig;

Run Code Online (Sandbox Code Playgroud)

服务器配置文件

const nodeExternals = require('webpack-node-externals');
const path = require('path');
const common = require('./webpack.common-config');

const serverConfig = {
  ...common,
  mode: 'production',
  name: 'server',
  target: 'node',
  devtool: false,
  externals: [nodeExternals()],
  entry: {
    server: ['@babel/polyfill', path.resolve(__dirname, 'src', 'server.js')],
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    }
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: '[name].js',
    chunkFilename: "[id].chunk.js"
  },
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

module.exports = serverConfig;

Run Code Online (Sandbox Code Playgroud)

通用配置文件

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const common = {
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [path.resolve(__dirname, 'src')],
        query: {
          presets: [
            ['@babel/preset-env', {loose: true, modules: false}],
            "@babel/preset-react"
          ],
          plugins: [
            "@babel/plugin-proposal-class-properties"
          ]
        },
      },
      {
        test: /\.css$/,
        use: [
            {
                loader: MiniCssExtractPlugin.loader,
            },
            'css-loader'
        ]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new OptimizeCSSAssetsPlugin(),
    new MiniCssExtractPlugin({
      filename: "styles.css",
    })
  ],
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin()]
  },
};

module.exports = common;

Run Code Online (Sandbox Code Playgroud)

另一个文件基本上合并了客户端和服务器配置。

我跑npm run build了,我跑了webpack -p --mode=production --optimize-minimize && node ./build/server.js

我收到以下警告:

    WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
    This can impact web performance.
    Assets: 
      vendor.js (667 KiB)
    
    WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
    Entrypoints:
      client (928 KiB)
          vendor.js
          styles.css
          client.js
Run Code Online (Sandbox Code Playgroud)

对于上述尺寸警告的任何建议或想法都会很棒!谢谢!

Ali*_*eza 5

我建议您尝试core-js而不是babel/pollyfill这样可以帮助您减少捆绑包的大小。

另外,我建议您尝试使用react-loadable支持 SSR 的动态导入。拆分代码有不同的策略。你可以在这里阅读更多(最重要的一个)

如果您使用 CSS 框架(例如 bootstrap),您应该只使用您需要的部分,并避免导入所有部分。有一个工具可以清除未使用的 CSS,名为 purgecss,但请谨慎使用,而且您必须知道自己在做什么。

如果您使用 lodash 或 material-ui 等库,您应该专门导入您的模块,以避免将所有包导入您的包中。

经验: import debounce from 'lodash/debounce'

npm dedup或者yarn dedup可以帮助删除 bundle 中的重复依赖项。