The first thing to do is to install CSS Loader
NPM Install Css-loader Style-loader--save-dev
Then configure the following code in the Webpack.config.js
It means to load the CSS file with Css-loader and then add it to the page with Style-loader.
Create a component.css file in the app directory
body{ background-color:red;}
Introduction of CSS files in app/index.js
Run the NPM run Start command.
We can see the whole background of our browser turned red.
What did Webpack do?
See the following code in Build/app.js.
And look at the index.html file we produced.
Strange, and there is no introverted style and no introduction of CSS files, then why is the browser red?
We open the debugging tool in the browser.
The original style is here!
Webpack dynamically adds a restrained style to the code.
If there is a lot of collaborative development in the case, there will be a lot of code naming duplicates, if this happens?
Let's test it out.
Add two CSS files to the app directory, style1.css
body{ background-color:red;}. class1{
Color:green;}
and Style2.css
body{ Background-color:black;}. class1{ Color:blue;}
The introduction of these two files in Index.js
Modify the Component.js file so that it adds an incoming class name to the element
Add the following configuration in Webpack.config.js
We execute the NPM run Start command if you see
The package is successful.
Open Browser http://localhost:8080/
You can see that the same class names are displayed properly, looking at the document structure on the right, and discovering that our class name is not Class1.
The original CSS modules the name of our class hash, we no longer have to worry about colleagues and we have the same name.
Isn't it convenient?
Let us face another problem, now in this case the CSS is JS dynamic add up, if when the JS file has a long time blocking event, the page will be in a long time without style state.
This is what we do not want to see, how to separate the CSS file and js file it?
First we need to install a plugin
NPM Install Extract-text-webpack-plugin--save-dev
After successful installation, add the following configuration in Webpack.config.js
When you are done, run NPM run start
Open Browser http://localhost:8080/
You can see that our two CSS files are merged into one app.css file and loaded as an external style sheet.
and the CSS file than the JS file to request first, so as to avoid the page will appear fouc-flas of Unstyle content no style contents flicker.
Webpack about the loading of CSS is here.
Webpack Tutorial--css Loading