How to split external styles into named bundles in angular

How to split external styles into named bundles in angular
Photo by Damir Spanic / Unsplash

Sometimes we’d like to split third-party external styles or legacy styles into a separate CSS bundle on building our angular application. This can be done quite easily. Keep reading to know more.

Including External Styles

As commonly known, we can include any external styles in our angular application by adding them to the styles array in our angular.json file:

"styles": [
  "styles/bootstrap.scss",
  "styles/app.scss",
  "styles/some-other-style.scss"
]
angular.json

This would generate a single CSS file after the ng-cli build goes through (ng build) :

dist/styles.<some-random-hash>.css

In Production build, angular generates a random hash in for browser cache busting purposes. If something changes in our bundle, a new hash is generated and added to the file name, by doing so we invalidate a previously cached file and force the browser to retrieve the new file from our server.

Quick Tip: If you want to extract CSS in ng-serve, as well as ng build, you can edit your angular.json file and add "extractCss": true to architect -> build -> options . We could previously pass the --extract-css flag to our ng build command but unfortunately, this is not supported after Angular 6+

Using Object Notation

We can also pass config objects to the style array using the object notation defined here to include external styles in our angular application:

"styles": [
  {
    "input": "styles/bootstrap.scss",
    "bundleName": "bootstrap"
  },
  {
    "input": "styles/app.scss",
    "bundleName": "app"
  },
  {
    "input": "styles/legacy.scss",
    "bundleName": "legacy"
  },
]
angular.json

and this will output 3 separate CSS files:

  • dist/bootstrap.<some-random-hash>.css
  • dist/app.<some-random-hash>.css
  • dist/legacy.<some-random-hash>.css

We learnt how we can easily split our external into separate named bundles. This can be useful for tracking bundle stats.

Conclusion

We learnt how we can easily split our external styles in angular into separate named bundles. This can be useful for tracking bundle stats.

Happy Engineering!