【问题标题】:React webpack bundle size is largeReact webpack 包大小很大
【发布时间】:2021-07-12 03:48:25
【问题描述】:

我有一个使用 react 开发的网站,它只有一个页面,但生产包大小为 1.11 MiB。我正在为这个应用程序使用 firestore、firebase 存储、material-UI、react-redux 运行良好,除了包大小之外一切都很好。

我使用 webpack-bundle-analyzer 来分析包大小,似乎 nodemodules 占用了很大的大小。在这里,我添加了屏幕截图。

我的 webpack 配置文件

    const path = require('path');
var CompressionPlugin = require('compression-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  mode: 'production',
  entry: './src/public/index.js',
  plugins: [
    new BundleAnalyzerPlugin({
      generateStatsFile : true
    }),
    new CompressionPlugin({
      deleteOriginalAssets: false,
      filename: "[path][base].gz",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      // Compress all assets, including files with `0` bytes size
      // minRatio: Infinity

      // Compress all assets, excluding files with `0` bytes size
      // minRatio: Number.MAX_SAFE_INTEGER
      minRatio: 0.8,
    })

  ],
  optimization: {
    nodeEnv: 'production',
    minimize: true,
    concatenateModules: true,

  },

  module: {
    rules: [{
        test: /\.(jpe?g|png|gif|svg)$/,
        loader: 'image-webpack-loader',
        // This will apply the loader before the other ones
        enforce: 'pre',
      },
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: [
              ["@babel/plugin-proposal-object-rest-spread", {
                "definitions": {
                  "process.env": {
                    "NODE_ENV": "\"production\""
                  }
                }
              }],
              ['babel-plugin-transform-imports',
                {
                  '@material-ui/core': {
                    // Use "transform: '@material-ui/core/${member}'," if your bundler does not support ES modules
                    'transform': '@material-ui/core/esm/${member}',
                    'preventFullImport': true
                  },
                  '@material-ui/icons': {
                    // Use "transform: '@material-ui/icons/${member}'," if your bundler does not support ES modules
                    'transform': '@material-ui/icons/esm/${member}',
                    'preventFullImport': true
                  }
                }
              ]
            ]
          }
        }
      }

    ]
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js'
  }
};

我不知道我在这里错过了什么来减少节点模块的大小。如果我们有任何其他减小捆绑包大小的选择,请给我一个建议。

【问题讨论】:

  • 对于 lodash ,您可以通过像 import { isEqual } from 'lodash'; 这样的结构导入来进行一些优化,然后将 sideEffect:false 添加到您的包 json 中
  • 你可能想探索将你的 js 文件分割成块
  • 有时捆绑包很大是正常的。您可以使用延迟加载,这样客户端就不需要一次下载完整的包。您可以访问reactjs.org/docs/code-splitting.html了解更多信息。
  • @Spring 我使用了 lodash 的 mapKeys 函数,现在我为此添加了 javascript 函数并删除了 lodash 代码,它减少了 64 kb
  • 也可以尝试使用 preact-compat 的 Preact,这应该是 React 的 10 倍大小,同时保留了与 React 相同的 API。

标签: reactjs firebase webpack material-ui node-modules


【解决方案1】:

MaterialUI、lodash 和 webpack 支持 Tree Shaking。 由于您使用了 webpack-bundle-analyser,我假设您的构建过程使用了 webpack。所以你的选择如下:

你可以使用Webpack的Tree Shaking Guide。

Material UI 还有一个Minimizing Bundle Size 指南。

一般来说,压缩包大小的很大一部分是消除死代码。

完成此操作后,您可能需要遵循 React 的 Code Splitting 指南以确保初始加载更快。

【讨论】:

    【解决方案2】:

    您可以单独导入 lodash 函数

    import get from 'lodash/get'
    

    而不是

    import { get } from 'lodash'
    

    但我敢打赌,这不会大大减少您的捆绑包大小

    【讨论】:

    • 我使用了 lodash 的 mapKeys 函数,现在我为此添加了 javascript 函数并删除了 lodash 代码,它减少了 64 kb
    【解决方案3】:

    确保您在生产模式下运行 webpack。为此,您可以使用 -p 标志运行 webpack,如下所示:

    webpack -p
    

    这个小标志做了这两件事来优化你的包大小:

    1. 使用 UglifyJs 启用缩小。它去除了不必要的白色 空格、新行、无法访问的代码等。
    2. 将 NODE_ENV 设置为“生产”。这告诉了一些包,比如 React,不包含调试代码。

    如果它不适合你,请尝试this

    【讨论】:

    【解决方案4】:

    如果你想减小构建大小,可以通过这种方式导入函数

    import groupBy from 'lodash/groupBy';
    

    不是这个

    import { groupBy } from 'lodash';
    

    前者会获取整个 lodash 库的内容,而后者只会获取其中的一个特定块。从而大大减少了构建大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2016-12-22
      • 2017-09-01
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 2016-03-18
      相关资源
      最近更新 更多