PacktPublishing / Webpack-5-Up-and-Running

Webpack 5 Up and Running, published by Packt
MIT License
17 stars 12 forks source link

Dealing with huge bundle size #69

Open franclin opened 1 year ago

franclin commented 1 year ago

Hello, I built a project whose bundle JS is over 16 MiB. The project makes use of the MERN stack and Material UI for the front-end and use SSR.

Below is the webpack 5 config file:

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

// Setting the assets path
const ASSET_PATH = process.env.ASSET_PATH || path.join('build', path.sep);

const clientConfig = {
  mode: "development",
  entry: {
    'bundle' : path.resolve(__dirname, 'client', 'client.js')
  },
  devtool: 'eval-source-map',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env'],
        },
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        // dependency: { not: ['url'] },
        type: 'asset/resource',
        generator: {
          //emit: false,
          publicPath: ASSET_PATH,
        },
      },
      {
        test: /\.(csv|tsv)$/i,
        use: ['csv-parser'],
      },
    ]
  },
  plugins: [
    new BundleAnalyzerPlugin({generateStatsFile : true})
  ]
}

const serverConfig = {
  name: "server",
  mode: "development",
  // entry: './server/server.js',
  entry: path.resolve(__dirname, 'server', 'server.js'),
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'server.generated.js',
    libraryTarget: "commonjs2",
    // clean: true,
  },
  //cache: true,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env'],
        },
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        //dependency: { not: ['url'] },
        generator: {
          publicPath: ASSET_PATH,
          //emit: false,
        },
        type: 'asset/resource',
      },
      {
        test: /\.(csv|tsv)$/i,
        use: ['csv-parser'],
      },
    ]
  }
}

module.exports = [clientConfig, serverConfig];

Any tips on how to optimize it?

tomowens08 commented 1 year ago

If the size is the issue, Webpack 5 allows for federations, splitting the bundle into smaller parts, if that helps?