javascript - Webpack 代码拆分影响 Web 性能

标签 javascript reactjs webpack bundle code-splitting

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

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;

serverConfig.js
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;

commonConfig.js
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;

另一个文件基本上合并了客户端和服务器配置。
我跑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
对于上述尺寸警告的任何建议或想法都会很棒!谢谢!

最佳答案

我建议你试试core-js而不是 babel/pollyfill这可以帮助您减少 bundle 的大小。
另外,我建议您尝试使用 react-loadable 进行动态导入。支持SSR。拆分代码有不同的策略。你可以阅读更多here (最重要的一个)
如果您使用 CSS 框架(例如 bootstrap),您应该只使用您需要的部分,并避免全部导入。有一个用于清除未使用的 CSS 的工具,名为 purgecss,但请谨慎使用,您必须知道自己在做什么。
如果您使用诸如 lodash 或 material-ui 之类的库,您应该专门导入您的模块以避免将所有包导入到您的包中。
经验:import debounce from 'lodash/debounce' npm dedupyarn dedup可以帮助删除 bundle 中的重复依赖项。

关于javascript - Webpack 代码拆分影响 Web 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62835353/

相关文章:

javascript - JQuery 选择器的误解

javascript - 从 pyqt QWebEngineView 启动 javascript 函数

javascript - react 引用 : Cannot read property 'focus' of null

node.js - 如何解决此错误 : "internal/modules/cjs/loader.js:638 throw err; ^"

node.js - 如果 root 的主要版本与依赖项不同,如何删除重复的 npm 包

javascript - ExtJS 4 到 ExtJS 5 的迁移

javascript - 我可以避免在每个 JavaScript 文件中调用 $(document).ready() 吗?

reactjs - 如何模拟从第三方库导出的类?

reactjs - Material UI TextField 多行,仅在按下 Shift Enter 时才换行

Webpack开发服务器缓存清理