As we saw in the last course, webpack can handle js
and json
file !
But what happened if we need to import css file ?
Add css file
We need add a new entry point to your application since we have no entry file for css file yet !
webpack.config.js
entry: {
myApp: [
"./src/style.css",
"./src/main.js",
],
},
style.css
.toto {
color: blue;
}
Let's go to build
this !
ERROR in ./src/style.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .toto {
| color: blue;
| }
What? why?
Loader
As we saw before, webpack only handle js
and json
file, but webpack let us to use loader
, this function is simple -> translate file to webpack in order to handle it !
For handle css file, we will use two loader !
module: {
rules: [
{
// Match file extension
test: /\.css$/,
// Order of loader from bottom to up
use: [
'style-loader',
'css-loader'
],
}
]
},
First css-loader
will resolve css import issue & return the css (It doesn't actually do anything with the returned CSS), and after style-loader
will inject css into the DOM !
So if we add a html file
index.html
<!DOCTYPE html>
<html>
<body>
<h1 class="toto">My First Heading</h1>
<p>My first paragraph.</p>
</body>
<script src="dist/bundle.js"></script>
</html>
We can see that your <h1>
is blue !
Conclusion
It's just a little example but if you use webpack, you will have a lot of loader, for exemple if you are using ts
you will need loader to handle .ts
file, if we need to import image we will need another loader etc...
Code here -> https://github.com/Code-Oz/webpack-academy/tree/5e80e4c080c156d1ebd261fc80e3c505d92473a7
I hope you want to learn more about webpack
in my academy !
I hope you like this reading!
🎁 You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and MP me 😁
Or get it HERE
☕️ You can SUPPORT MY WORKS 🙏
🏃♂️ You can follow me on 👇
🕊 Twitter : https://twitter.com/code__oz
👨💻 Github: https://github.com/Code-Oz
And you can mark 🔖 this article!
Top comments (4)
Great article!
Thanks abhishek!
Great thanks !
thanks Mogneur