大型typescript项目优化webpack编译速度

发布时间 2023-03-27 11:03:33作者: 让速不让路

Person:

  • A large typescript project takes a long time to start every time, using the default configuration of webpack5, is there any optimization solution?

ChatGPT:

  • Yes, there are several optimization techniques you can use to improve the performance of your TypeScript project with webpack5. Here are some suggestions:
  1. Use webpack's built-in caching mechanism: Webpack has a caching mechanism that can significantly speed up the build time of your project. By default, webpack uses a caching mechanism that caches compiled modules in memory. You can enable caching by setting the "cache" option to true in your webpack configuration file.
  2. Split your code into smaller chunks: Splitting your code into smaller chunks can help improve the build time of your project. You can use webpack's built-in code splitting feature to split your code into smaller chunks that can be loaded on demand. This can reduce the initial load time of your application.
  3. Use tree shaking to eliminate unused code: Tree shaking is a technique that eliminates unused code from your application. This can help reduce the size of your bundles, which can improve the build time of your project. To enable tree shaking in webpack, you can use the "optimization.usedExports" option.
  4. Use the production mode: When you build your project in production mode, webpack automatically applies several optimizations that can improve the build time of your project. To build your project in production mode, you can set the "mode" option to "production" in your webpack configuration file.
  5. Use a faster computer or use a distributed build system: If your project is particularly large and complex, you may need to use a faster computer or use a distributed build system to speed up the build time of your project. Distributed build systems like Jenkins or Travis can help you distribute the build process across multiple machines, which can significantly reduce the build time of your project.
  6. Use Webpack Bundle Analyzer to analyze your bundle size and identify opportunities for optimization: The Webpack Bundle Analyzer is a tool that can help you analyze your bundle size and identify opportunities for optimization. This can help you optimize your webpack configuration file to improve the build time of your project.

Person:

  • 2 / 2

ChatGPT:

  • Certainly! Here is an example configuration file for webpack5 that incorporates the optimization techniques mentioned above:
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'production', // Enable production mode
  entry: './src/index.ts', // Your entry point
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  optimization: {
    usedExports: true, // Enable tree shaking
    splitChunks: { // Split your code into smaller chunks
      chunks: 'all',
      minSize: 20000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      automaticNameDelimiter: '~',
      enforceSizeThreshold: 50000,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module) {
            // Extract the name of the package from the file path
            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
            return `npm.${packageName.replace('@', '')}`;
          },
        },
      },
    },
  },
  cache: true, // Enable caching
  plugins: [
    new webpack.ProgressPlugin() // Show build progress in console
  ]
};

This configuration file includes the following optimizations:

  • Production mode enabled
  • Tree shaking enabled using the "optimization.usedExports" option
  • Code splitting enabled using the "optimization.splitChunks" option
  • Caching enabled using the "cache" option
  • A progress plugin added using the "plugins" option

Note that this is just an example configuration file, and you may need to adjust it to fit your specific project needs.

Person:

  • Can you consider using a dll?

ChatGPT:

  • Yes, using a DLL (Dynamic Link Library) is another optimization technique you can consider to improve the build time of your TypeScript project with webpack5.

A DLL is a library that contains pre-compiled code that can be shared across multiple applications. In the context of webpack, a DLL can contain frequently used code, such as third-party libraries, that don't change frequently. By separating frequently used code into a DLL, you can reduce the build time of your project by compiling the DLL once and then referencing it from multiple applications.

Here's how you can use a DLL with webpack5:

  1. Create a DLL configuration file: Create a separate webpack configuration file for your DLL that compiles your frequently used code into a DLL. Here's an example configuration file for a DLL:
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'production',
  entry: {
    vendor: ['react', 'react-dom'] // Add the packages you want to include in the DLL
  },
  output: {
    filename: '[name].dll.js',
    path: path.resolve(__dirname, 'dll'),
    library: '[name]_dll' // Set the name of the DLL
  },
  plugins: [
    new webpack.DllPlugin({
      name: '[name]_dll', // Set the name of the DLL
      path: path.resolve(__dirname, 'dll/[name].manifest.json')
    })
  ]
};
  1. Build the DLL: Build the DLL by running webpack with the DLL configuration file:
webpack --config webpack.dll.config.js
  1. Reference the DLL in your project: In your main webpack configuration file, add a reference to the DLL by using the "DllReferencePlugin". Here's an example configuration file that references the DLL:
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'production',
  entry: './src/index.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  optimization: {
    usedExports: true
  },
  plugins: [
    new webpack.DllReferencePlugin({
      manifest: require('./dll/vendor.manifest.json')
    })
  ]
};

In this configuration file, the "DllReferencePlugin" is used to reference the DLL. The "manifest" option is used to specify the path to the manifest file generated by the DLL configuration file.

Using a DLL can significantly improve the build time of your project, especially if you have frequently used code that doesn't change frequently. Note that the example configuration files I provided are just examples, and you may need to adjust them to fit your specific project needs.