Webpack: Managing Tree Shaking

PROBLEM

Sometimes, Webpack’s tree-shaking may accidentally eliminate imported code from import statements.

For example, we may have a root JS file that imports a CSS file:-

import React from 'react';
import ReactDOM from 'react-dom';
import '../css/index.css';

...

… and for some reason, the CSS file will never appear in the final bundle even if the Webpack config contains proper rules to handle CSS files.

SOLUTION

To prevent Webpack from removing any “unreferenced” code (ex: global CSS files, JS polyfills, etc), list these side effects under package.json, for example:-

{
  "name": "front-end-stack",
  "sideEffects": [
    "*.css"
  ]
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s