我的 webpack 在 React Express 项目中捆绑代码的速度非常慢

问题描述 投票:0回答:1

我有一个包含 React 和 Express 的整体应用程序。每次我更改代码时它都会捆绑在一起,并且需要 30 秒才能更新屏幕上的更改。构建时间约为 30 至 50 秒。我的 webpack 配置文件是这样的

//webpack.config.js
import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';
import nodeExternals from 'webpack-node-externals'
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';

import pkg from '../package.json';

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze = process.argv.includes('--analyze') || process.argv.includes('--analyse');


const config = {
  context: path.resolve(__dirname, '..'),

  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
  },
  mode: isDebug ? 'development' : 'production',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [
          path.resolve(__dirname, '../src'),
        ],
        query: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            ['@babel/preset-env', {
              targets: {
                browsers: pkg.browserslist,
              },
              modules: false,
              useBuiltIns: false,
              debug: false,
            }],
            '@babel/preset-react',
          ],
          plugins: ['react-intl'],
        },
      },
      {
        test: /\.css$/,
        use: [
          'isomorphic-style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
              minimize: !isDebug,
              discardComments: { removeAll: true },
            }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash:8]' : '[hash:8].[ext]',
        },
      },
      {
        test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash:8]' : '[hash:8].[ext]',
          limit: 10000,
        },
      },
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader',
      },
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
    warnings: isDebug
  },
};

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['babel-polyfill', './src/clientLoader.js'],
  },
  optimization: {
    ...(isDebug ? {} : {
      minimize: true,
      minimizer: [new TerserPlugin({
        terserOptions: {
          mangle: {
            reserved: ['Td', 'Tr', 'Th', 'Thead', 'Table'],
          },
        },
      })],
    }),
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      automaticNameDelimiter: '~',
      automaticNameMaxLength: 30,
      name: true,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  },
  output: {
    ...config.output,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug ? '[name].chunk.js' : '[name].[chunkhash:8].chunk.js',
  },

  plugins: [
    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    new AssetsPlugin({
      path: path.resolve(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),

    ...isAnalyze ? [new BundleAnalyzerPlugin()] : [],
  ],

  devtool: isDebug ? 'cheap-module-source-map' : false,

  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
 
export default clientConfig;

我的打包文件是这样的

//build.js

import cp from 'child_process';
import run from './run';
import clean from './devClean';
import copy from './copy';
import bundle from './bundle';
import render from './render';
import pkg from '../package.json';


async function build() {
  await run(clean);
  await run(copy);
  await run(bundle);

  if (process.argv.includes('--static')) {
    await run(render);
  }

  if (process.argv.includes('--docker')) {
    cp.spawnSync('docker', ['build', '-t', pkg.name, '.'], { stdio: 'inherit' });
  }
}

export default build;

我用

npm run dev
为了在开发模式下运行我的代码

我的package.json是这样的:

{
  "name": "rentall",
  "version": "3.4.2",
  "private": true,
  "engines": {
    "node": ">=10",
    "npm": ">=5.10"
  },
  "browserslist": [
    ">1%",
    "last 4 versions",
    "Firefox ESR",
    "not ie < 9"
  ],
 
  "scripts": {
    "test": "mocha \"src/**/*.test.js\" --require @babel/register --require test/setup.js",
    "test:watch": "yarn run test -- --reporter min --watch",
    "clean": "babel-node tools/run clean",
    "copy": "babel-node tools/run copy",
    "extractMessages": "babel-node tools/run extractMessages",
    "bundle": "babel-node tools/run bundle",
    "build": "babel-node tools/run build --openssl-legacy-provider --inspect --max_old_space_size=4096",
    "build:stats": "yarn run build -- --release --analyse",
    "deploy": "babel-node tools/run deploy",
    "render": "babel-node tools/run render",
    "serve": "babel-node tools/run runServer",
    "start": "babel-node tools/run --openssl-legacy-provider --inspect start",
    "devBuild": "babel-node tools/run devBuild --openssl-legacy-provider --inspect --max_old_space_size=4096",
    "dev": "nodemon --exec 'npm run devBuild && npm run serve' --config nodemon.json"
  }
}

我尝试将我的 webpack 更新到版本 5,但它太复杂,这就是为什么我无法在 v5 中运行我的捆绑程序。然后我看到了文章说v5在webpack中比v4慢30%

reactjs express webpack babeljs bundler
1个回答
0
投票

您可以尝试将

devtool
cheap-module-source-map
设置为
eval

devtool
配置定义了源映射的样式以增强调试过程,该值可以显着影响构建和重建速度。
eval
值是具有最高性能的开发构建的推荐选择。这应该可以缩短您的构建时间。

devtool: isDebug ? 'eval' : false,
© www.soinside.com 2019 - 2024. All rights reserved.