Recap about Webpack

What is Webpack?

Webpack is a module bundler, it helps pack our application from multiple files to one or a few files which can run on target environments ( ex: web browser).
For example with a modern react application, we have many files: css, scss, fonts, image, js, jsx and in each file we also import/use other files. Webpack help we pack their files together in a bundle file and it can run in the web browser

Why we need Webpack?

Assume we don’t have Webpack or any module bundler and we have a React web application.
To our web can run in a web browser correctly, at least we need:

  • index.html file.
  • The index.html file needs a script tag with a link to the React library source.
  • in index.html file need a script tag with a link to the React DOM library source.

Depending on the requirement, we usually need style ( add some style sheet tags to link to CSS files) and other script tags to other libraries. A complex project is very hard to manage.
Webpack can help us by easily defining the relationship in our app by using import statements. Webpack will auto pack code needed for our app run.

How Webpack work?

Internally, Webpack begins at an entry file ( usually index.js file ), and from this file, it builds a dependency graph of our application. From this graph, Webpack can produce a bundle file that has all the resources, codes, and libraries necessary for the app to run.
With every import, it is a command say Webpack that is a dependency.

Components of Webpack

  • Entry:
    • Use to indicate where Webpack begin to build dependency graph
  • Output
    • Use to indicate where and name of bundle files
  • Loaders
    • By default, Webpack only understand and bundle JS and JSON file
    • Loader helps Webpack understand other file types and build a dependency graph
  • Plugins
    • This component helps Webpack can do tasks like bundle optimization, asset management, injection of environment variables, minify, …

Conclusion

Webpack has many loaders and plugins to help us build a modern application ( not only web, it can use to bundle other applications like Rail, …)
We can also write custom loaders and plugins to extend the function of Webpack