Webpack + React + Loading CSS of external modules

2019-05-26 13:21发布

Webpack/CSS Experts!

My NodeJS/React application has the following structure, where I use Webpack 3.8.1 to package & bundle files.

-app
  |--actions
  |--constants
  |--components
  |--containers
  |--css
  |--reducers
  |--store
-common
-server
-webpack
  |--rules
       |--css
       |--javascript
  |--externals
  |--paths
  |--resolve
  |--webpack.config.js

Everything works as expected in development and production but there is one problem that I have been struggling with: External node modules CSS. When I add a new dependency, which comes with some sort of CSS/SCSS/SASS stylesheets and for that matter makes use of className to style different components, I hit FOUC CSS where none of the external node module's CSS styles has been recognized and therefore are missing from the map that webpack 3 creates once the build process is complete.

As an example, I am using Material-UI as a dependency and so far everything works but when attempting to do the following:

<IconButton>
    <FontIcon className="muidocs-icon-action-home"/>
</IconButton>

... and nothing is displayed. This is just one example and I have been facing this issue with other node modules too! So I believe there is something wrong with my webpack configurations or the way I am loading CSS modules. For your reference, I have created a gist of all webpack configuration files.

I have come across with some similar questions like this but am not sure if that will help long-run as my project is becoming bigger.

Your helps & thoughts are greatly appreciated!

[Note] As a side note, and apart from external CSS modules, when I add a new CSS declaration to main.css, I still need to have something like:

import classNames from "classnames/bind";
import styles from "../../../css/components/timeline.css";
const cx = classNames.bind(styles);

within import section and later do something like this:

<div ref="container"
     className={cx("calendar-style")}/>

to have CSS styles correctly applied, which again I suspect isn't optimal. As I mentioned earlier, webpack creates a hashmap of all CSS styles inside a .css file under public, whose content look something like this:

._1zvVaiwSh1X6O03wrS2gD- {
    height: 100%;
    padding: 0;
    margin: 0;
}
._2W0FVEAQcsYxEbCbWHcCE3 {
    height: 100%;
}...

Therefore, failing to use cx as stated above, will have the same problem as explained earlier and none of my CSS styles are applied. So, a following question would be: how webpack creates these hashes and why? How to control them being generated or not?

0条回答
登录 后发表回答