Search code examples
reactjsbundlewebpack-4font-awesome-5

Move fontawesome to own bundle using dynamic import


I am trying to reduce my bundle size by splitting it into several chunks. BundleAnalyzerPlugin tells me that Fontawesome is imported in full even though I have tried to only import the icons I need which seems odd.

Fontawesome

My fontawesome imports

import { library } from '@fortawesome/fontawesome-svg-core';
import { faBell, faEyeSlash, faEye} from '@fortawesome/free-solid-svg-icons';
import { faBell as regularBell} from '@fortawesome/free-regular-svg-icons';

...
library.add( faBell, faEye, faEyeSlash, regularBell, regularCalendarAlt)

My fontawesome version

"@fortawesome/fontawesome": "^1.1.5",
"@fortawesome/fontawesome-free-regular": "^5.0.10",
"@fortawesome/fontawesome-free-solid": "^5.0.10",
"@fortawesome/fontawesome-svg-core": "^1.2.8",
"@fortawesome/react-fontawesome": "^0.1.3",

I am trying to use the import() splitting technique described here but can't figure out how to make it work for Fontawesome.

return import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
  ...
}

How can I put split fontawesome into it's own bundle and load it synchronously?

Something along the lines of Prefetching/Preloading would work too, but those techniques seems to have very poor browser support? I sadly need support for Safari.

My webpack config

  // Set up webpack plugins
  config.plugins = [
    nodeEnvPlugin,
    firebasePlugin,
    cssExtractPlugin,
    new BundleAnalyzerPlugin(
      {
        excludeAssets: /node_modules/,
        statsOptions: {
          exclude: /node_modules/
        }
      }
    )
  ]

BundleAnalyser result

Kind regards /K


Solution

  • You're trying to view node_modules which shouldn't be part of your bundle upon deployment. You should be configuring your BundleAnalyzerPlugin to view the destination of webpack output instead. That way you could fully identify which are consuming big in terms of size.

    Here's the option about it from your library of choice:

    https://github.com/webpack-contrib/webpack-bundle-analyzer#bundledir

    Here is mine implementing the same technique you have above on fontawesome optimization

    enter image description here

    Here's my repo for your reference: https://github.com/crrmacarse/crrmacarse.github.io