How to Install Webpack?
Webpack is an open-source JavaScript module bundler. It allows you to split your JavaScript into separate modules in development while letting you compile those modules into a single bundle in production.
Webpack Main Concepts
Entry: The entry point is the module that webpack uses to start building its internal dependency graph. From there, it determines which other modules and libraries the entry point depends on (directly and indirectly).
Output: the output property instructs webpack where to emit the bundle(s) and what name to use for the file(s).
Loaders: By default, webpack only understands JavaScript and JSON files. To process other types of files and convert them into valid modules, webpack uses loaders.
Plugins: Plugins are used for any other task that loaders can’t do. They provide us with a wide range of solutions about asset management, bundle minimization and optimization, and so on.
Mode: Typically when we develop our application we work with two types of source code — one for the development build and one for the production build. Webpack allows us to set which one we want to be produced by changing the mode parameter to development, production, or none.
Installation of Webpack
Install webpack is by using a package manager. We will go with npm.
npm install webpack --save-dev
In the root directory of your project add a file called webpack.config.js.
webpack.config.js
var path = require('path');
The entry option tells webpack which is our main JavaScript file. In the output, we specify the name and path of our bundle. After running webpack we will have all our JavaScript in a file called bundle.js. This is the only script file that we will link in our HTML:
<script src="./dist/bundle.js"></script>
Add these lines to your package.json:
//...
"scripts": {
"build": "webpack -p",
"watch": "webpack --watch"
},
//...
Now by calling npm run build
from the terminal we can make webpack bundle our files (the -p option stands for production and minifies the bundled code). Running npm run watch will start a process that automatically bundles our files when any of them change.