Code Splitting in Webpack 3 - CSS Bundle
As I promised in part 2, this time we will take a look at how to separate css
into a single file.
If you use webpack
before, you know that webpack
treating everything as an dependency, not just js
, but everything. This is the mighty power of webpack
.
So if you want to use css
or sass
in your code, you need to specify like this:
|
|
Then you need to use loader to convert these files because webpack
default will treat everything as js
.
|
|
Under the hood,
webpack
will use acron
to generate AST (abstract syntax tree) so it can analyze the code. That’s how webpack
generate dependency trees, optimize the code etc.If we don’t use loader to convert the non -
js
files, the AST will fail. Hence bundle errors.Also by default, webpack
will load the css
as an js
function and they will scatter in different places just as other functions. As tradition, we tend to put them into a single file. webpack
also allow us to do that by using extract-text-webpack-plugin
.
See the pattern? To
webpack
, everything is a plugin :rocket:
Let’s take a look at the example webpack
provided in its repo.
The example
In this example, we have a example.js
, which will use style.css
(which will style the whole html page’s background
) and also chunk.js
. In chunk.js
, it will use style2.css
to change the background
of class xyz
.
|
|
|
|
Normally we will use the configuration similar to this:
|
|
The result will be like the following:
|
|
webpack
will generate js
file, but not css
file by default.
If we want to generate a separate css
file, we need to modify our configuration file to this:
|
|
Now if we run command webpack
, we will get the following result
|
|
There’s our style.css
which includes all the styles we defined (to be more precise, it contains all the styles we used).
That’s how you do css bundle in webpack
!
Happy hacking!