material-components / material-components-web

Modular and customizable Material Design UI components for the web
https://material.io/develop/web
MIT License
17.15k stars 2.15k forks source link

[bug] Add CSS files to "sideEffects" in package.json #4702

Open richiksc opened 5 years ago

richiksc commented 5 years ago

When running a production build in Webpack with tree-shaking, the CSS files are removed as they are being imported as side effects. In a JavaScript file for your project such as index.js:

import '@material/ripple/dist/mdc.ripple.min.css'

In a development build this works fine, but when webpack is run in production mode with tree shaking enabled, side-effect imports are removed unless specifically declared in the "sideEffects" field of package.json.

What MDC Web Version are you using?

@material/ripple 2.1.1

What browser(s) is this bug affecting?

Observed in Chrome 74, but most likely affects all browsers.

What OS are you using?

Windows 10 version 1809.

What are the steps to reproduce the bug?

  1. Set up a simple Webpack project with an HTML file with a ripple element and a javascript file that imports the CSS and MDCRipple JS and attach it to the aforementioned element. Make sure to include style-loader or css-loader.
  2. Run a Webpack build in development mode, start a server, and observe. The ripple is there as expected.
  3. Run a Webpack build in production mode with tree-shaking enabled, start the server, and observe. The ripple JS behavior is there (custom properties are assigned, event listeners are attached), but none of the CSS is there - no ::before pseudo element or visible indication of the ripple or hover states. This is because Webpack strips out the CSS import as we are not importing any symbols from it which we are using in JavaScript. This can be avoided by marking CSS files as side effects in package.json.

What is the expected behavior?

The ripple is visible in a site built with Webpack in production mode.

What is the actual behavior?

The ripple is not.

Any other information you believe would be useful?

This can be fixed easily by replacing the "sideEffects": false line in package.json with "sideEffects": ["*.css"]

moog16 commented 5 years ago

Confirmed this is happening in sample webpack project below:

sideEffects.zip

to view, ungzip and run:

npm i
npm run build
# open index.html

Notice that the checkbox is unstyled. This can be remedied by running webpack in --mode=development. Change package.json, build script to:

"build": "webpack --mode=development",

We should prioritize this. What do you think, @abhiomkar ?

richiksc commented 5 years ago

Development mode leaves out optimizations critical to performance. Currently I remedy this with a hack to trick the parser into thinking the import is being used, like this:

import mdcRippleCss from '@material/ripple/dist/mdc.ripple.min.css'

mdcRippleCss; // hack