Load css files with webpack 3.3


Here we can see  how to load the external css files with webpack.

Webpack is  automatically creates the link tag and add to our html file.
So, we can easily load the module specific css.

To play with the css files in webpack we need to install npm module named "style-loader", "css-loader" .

Install css loaders for webpack.
npm install --save style-loader css-loader

Once we are done with the installation we  can import the css file by using the below statement in js file.
import '../css/styles.css';


 From  above code,  style tag will create and all css styles are added into DOM as inline styles.

But, this is not what we want because If we take the large scale project thousands of lines css will be there.
We can't add all of them into the DOM.



Webpack people giving us the feature to include the file as link tag in header.
let's see how can we do this with webpack.

import url from 'styles.css'

Also install file-loader module.
npm install file-loader

Check this to load the external css files.
webpack.config.js

index.js






Here one more beautiful feature in webpack is accessing the css files dynamically.
i.e we can change the css and load the css conditionally.

To achieve this functionality we have "transform" property.
 transform:
        A transform is a function that can modify the css just before it is loaded into the page by the style-loader.
This function will be called on the css that is about to be loaded and the return value of the function will be loaded into the page instead of the original css. If the return value of the transform function is falsy, the css will not be loaded into the page at all.

Here the code snippet for the change the css.


transform.js



conditionalCss.js







No comments:

Post a Comment