Search code examples
webpackbabeljswebpack-4babel-loaderbabel-polyfill

Webpack 4 bundle size after upgrade from Webpack 3


After migrating my project from Webpack 3 and Babel 6 to Webpack 4 and Babel 7 then bundle size has increased. The project compiles fine, but the bundle size is now 1MB larger than before. I have been working hard to decrease the bundle size so this behaviour was a little dissapointing. I am apparently missing something. 「(°ヘ°)

My old webpack.config.js (Webpack 3)

const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

process.env.NODE_ENV = process.env.NODE_ENV || 'development'

if (process.env.NODE_ENV === 'test') {
  require('dotenv').config({ path: '.env.test' })
} else if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({ path: '.env.development' })
} else if (process.env.NODE_ENV === 'production') {
  require('dotenv').config({ path: '.env.production' })
} else {
  require('dotenv').config({ path: '.env.development' })
}

module.exports = (env) => {
  const isProduction = env === 'production';
  const CSSExtract = new ExtractTextPlugin('styles.css');

  return {
    entry: ['babel-polyfill', './src/app.js'],
    output: {
      path: path.join(__dirname, 'public', 'dist'), //absolute path
      filename: 'bundle.js'
    },
    module: {
      rules: [{
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: [
          /node_modules/,
          /firebase-functions/
        ]
      }, {
        test: /\.s?css$/,
        use: CSSExtract.extract({
          use: [
            {
              loader: 'css-loader',
              options: {
                sourceMap: true
              }
            }, {
              loader: 'sass-loader',
              options: {
                sourceMap: true
              }
            }

          ]
        })
      }, {
        test: /\.(png|jpe?g|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {},
          },
        ],
      }, {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      }]
    },
    plugins: [
      CSSExtract,
      new UglifyJSPlugin(),
      new webpack.DefinePlugin({
        'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
        'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
        'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
        'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
        'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
        'process.env.FIREBASE_MESSAGING_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGING_SENDER_ID),
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      }),
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new BundleAnalyzerPlugin(),
    ],
    devtool: isProduction ? 'source-map' : 'inline-source-map',
    devServer: {
      contentBase: path.join(__dirname, 'public'),
      historyApiFallback: true,
      publicPath: '/dist'
    }
  };
}

My new webpack.config.js (Webpack 4)

'use strict'
const path = require('path')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const TerserPlugin = require('terser-webpack-plugin')

process.env.NODE_ENV = process.env.NODE_ENV || 'development'
if (process.env.NODE_ENV === 'test') {
  require('dotenv').config({ path: '.env.test' })
} else if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({ path: '.env.development' })
} else if (process.env.NODE_ENV === 'production') {
  require('dotenv').config({ path: '.env.production' })
} else {
  require('dotenv').config({ path: '.env.development' })
}

module.exports = (env) => {
  const isDev = env === 'development'
  const bundleName = 'bundle.js'

  const firebasePlugin = new webpack.DefinePlugin({
    'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
    'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
    'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
    'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
    'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
    'process.env.FIREBASE_MESSAGING_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGING_SENDER_ID),
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  })

  const plugins = isDev ? 
  [
    firebasePlugin,
    new BundleAnalyzerPlugin()
  ] 
  : 
  [
    firebasePlugin,
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ]

  // build WEBPACK CONFIG
  const config = {}

  config.devServer = {
    contentBase: path.join(__dirname, 'public'), //absolute path
    historyApiFallback: true,
    publicPath: '/dist'
  }

  config.mode = env
  config.watch = isDev
  config.resolve = {
    extensions: ['.js', '.jsx']
  }
  config.devtool = 'source-map'

  config.entry = ['@babel/polyfill', './src/app.js']

  config.output = {
    path: path.join(__dirname, 'public', 'dist'), //absolute path
    filename: bundleName
  }

  config.optimization = {
    minimizer: [
      new TerserPlugin({
        sourceMap: isDev,
        cache: true,
        parallel: true,
        terserOptions: {
          mangle: false,
          keep_classnames: true,
          keep_fnames: true,
          output: {
            comments: false
          }
        }
      })
    ]
  }
  config.plugins = plugins;
  config.module = {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: [
        /node_modules/,
        /firebase-functions/
      ],
      use: {
        loader: 'babel-loader'
      }
    },
    {
      test: /\.svg$/,
      loader: 'svg-inline-loader'
    },
    {
      test: /\.css$/i,
      use: ['style-loader', 'css-loader'],
    },
    {
      test: /\.s[ac]ss$/i,
      use: [
        'style-loader', 
        'css-loader', 
        'sass-loader', 
      ],
    }
    ]
  }
  return config
}

With Webpack 3 my bundle size was 2.6M. It now weights in at 3.6M. :/ Have I missed something? How can I optimise Webpack to reduce bundle size?

Many thanks! K


Solution

  • I think there is something with your images (maybe all of the images inlined to your js?). Where is your file-loader configuration for webpack4? How do you load it now? I can help more if you will share resulting bundle for wp3 and wp4.

    There are optimizations i can see:
    1) set terserOptions.mangle to true. it will not rename your properties (because mangle.properties is disabled until you don't set mangle property to { properties: true }), bundle will work i think. and other terser options can be reduced
    2) babel/polyfill is a huge thing, you don't need it's full version. also, it was deprecated in favor of core-js@3. babel now have a nice feature useBuiltIns: usage which will include only polyfills you need to the bundle.