Webpack Dev Server Setup in 3 steps & Features | webpack-dev-server
webpack-dev-server setup guide and features |
What is Webpack?
Webpack is a module bundler for Javascript applications. Starting from entry point, it builds a dependency graph that maps to every module in your application and generates one or more bundles. Dependency graph which is nothing but dependency of one file on another(another js file or assets). Webpack helps you optimize bundle, code splitting, compressing the code and bunch of other things.
What is wepack-dev-server?
In simple terms, webpack-dev-server is a light Node.js Express server that serves the webpack bundles. As opposed to a normal server which servers files from hard disk, webpack-dev-servers serves it from the RAM. If you are bundling your application using webpack then their is no need of using another server during development.
Why webpack-dev-server?
- Auto Refresh: You can track your changes live without refreshing the page every time you make a code change. webpack-dev-server has a iframe mode in which page is embedded in iframe and refreshed when code changes. It also has Inline mode in which webpack-dev-server client entry is added to the bundle which reloads the page on change. With each mode you can do Hot Module Replacement, in which only the changed module refreshes.
- Takes care of front end: In general, you will be running only one server that will be responsible for back end heavy lifting as well as front end compilation. webpack-dev-server takes care of front end logic compilation in an optimal fashion. It serves the bundle that lives on RAM rather than hard disk.
Setting up webpack-dev-server?
-
- First install webpack-dev-server.
npm install webpack-dev-server --save-dev
-
- Add configuration for webpack-dev-server in webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/scripts/app.js',
output: { path: __dirname + '../dist/', filename: 'bundle.js' },
devServer: {
contentBase: path.join(__dirname, "../dist/"),
port: 5000,
}
};
-
- In package.json, update npm start script to use webpack-dev-server
"scripts": {
"start": "webpack-dev-server --config './webpack/webpack.config.js'"
}
-
- npm start to start webpack-dev-server
npm start
From Front End Interview perspective, you might get asked about how Webpack works.