Webpack configuration setup — part II
this article is the second part of a basic webpack setup for web applications.
- Webpack configuration setup — part I
- Webpack configuration setup — part II ( you are here)
in last article we saw how to bundle and serve javascript files in webpack.
now, let’s learn to serve our assets — styles, images etc.
serving styles (css, scss etc.)
- create a file
style.css
insrc
folder. - define below class for our loaded image from part 1
.img-sample { border: 2px solid red;}
3. now we will define our third important configuration for the webpack file. it’s called loaders
and is defined by module
property in webpack.config
file.
webpack can bundle all kinds of files but it understands only javascript. loaders transform all other kind of files into their javascript equivalents.
each loader takes a certain kind of file as input and transforms these files into modules to be included in our bundle. module
is an object type property which defines all the loader rules in a rules
array property. each loader rule needs two properties:
a. test — type of file to be transformed ( can be a regex pattern)
b. use — the loader to do this transformation, can be a simple string name of the loader or an object if we want more control
when webpack finds an
import
statement (egimport './style.css'
), it applies thetest
pattern to match with the filename. if it finds a match, the corresponding loaders are applied to transform this file into javascript.
for css files, we will be using style-loader
and css-loader
so let’s install these.
npm install --save-dev style-loader css-loader
and define loader module rules:
module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ]}
4. now if we import style.css
file in app.js
import './style.css';
and run
npm start
we can see our defined style applied to the loaded image. we can also include sass loaders to compile sass files into css for *.scss
files.
similarly, it’s easy to configure webpack loaders for other assets like images, fonts etc.
in next article, we will see how to configure webpack to auto insert the generated bundle in our html file, so we don’t have to do it manually.
<prev |next>