While learning react, many tutorials have recommend to use webpack for building react apps. I created a very simple react app on Github to demonstrate the concept of webpack.
What does Webpack do? Why do I need it when using React?
React encourages you to write reusable UI components. Let's say you write a date picker. It comes with its own CSS style sheet and a background image. To reuse this component elsewhere, you need to pack the source code along with all the resources into one package for others to download.
Webpack does just that:
fonts + images + CSS + source code => bundle.js
How does it work?
Download this example I wrote and take a look at the index.js file. On the third line of index.js you will see:
You might think this line is broken because how can you import a .css into a .js file. While, it works because of Webpack. Open up webpack.config.js and take a look at this part (starting at line 18):
Webpack uses loaders to deal with different file formats during the packing stage. In this case, css-loader and style loader are used to deal with .css file type. If you write in LESS or SASS, there are corresponding loaders to deal with those.
There are two ways to enable loaders, the most common way is to specify them in the webpack.config.js file:
All .png files will be dealt with the url-loader. What the url-loader does is to turn a file into data URI. In this case, the file small_img.png is turned into:
limit=300 part means if the file is less than 300 bytes, then turn it into data URI.
Another way to enable loader is shown on line 11 in index.js:
If you specify the loader this way, then it would only affect this particular jpg file rather than all the jpg files in your project.
The file-loader reads a file and return the file in the following format:
We don't want to reference a file with a hash name, instead we would like to reference it using the file's original name and extension.
name=[name].[ext] does just that.
Once all the loaders are being configured, run the
webpack command to transform the assets into data URIs or plain file names. Then, you can open up
index.html in the browser to see the result.
I hope this post provides a general overview of what Webpack does and how it fits into the big picture of react development.