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
- in index.html file need a script tag with a link to React library source
- in index.html file need a script tag with a link to React DOM library source
Depend on the requirement, usually, we need style ( add some stylesheet tags to link to css files), other script tags to other libraries. In a complex project, it very hard to manage
Webpack can help us by let we easy define the relationship in our's app by use import statement, Webpack will auto pack code need for our's 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's application. From this graph, Webpack can produce a bundle file have all resource, code, library necessary for app 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 help Webpack can understand other file types and build dependency graph
- Plugins
- This component helps Webpack can do tasks like bundle optimization, asset management, injection of environment variables, minify, ...
Conclusion
Webpack have many loaders and plugins help we build a modern application ( not only web it can use to bundle other application like Rail, ... )
We also can write custom loaders and plugins to extend function of Webpack (like)
Top comments (0)