Why use webpack-dev-server
In the development, we can find that it is not efficient to use Webpack and its command line tools for development and debugging. Every time after writing the code, we need to execute the NPM run build command to update the JS file, and then refresh the page to see the update effect. Webpack-dev-server is a handy local development tool that solves this problem.
Webpack-dev-server installation and configuration
Install with the following command:
npm install webpack-dev-server --save-dev
Copy the code
–save-dev: save the configuration of webpack-dev-server to the devDependencies node of pacjage.json. This is done because webpack-dev-server is only used for local development and is not needed in a production environment. NPM install– Production filters out redundant modules in devDependencies when the project goes live to speed up installation and distribution.
To easily start webpack-dev-server, we add a dev directive to package.json:
"scripts": {
"build": "webpack"."dev": "webpack-dev-server --open"//open is automatically executed to open the page}Copy the code
Finally, add a devServer object to webpack.config.js, which is dedicated to hosting the webpack-dev-server configuration. Webpack-dev-server can be thought of as a server whose main job is to receive browser requests and return resources. When the service starts, Webpack is first used to pack the modules and prepare the resources (bundle.js in the example). When Webpack-dev-server receives a resource request from the browser, it first verifies the URL address. If the address is a resource service address (publicPath configured above), the resource is looked for in the Webpack result and returned to the browser. Conversely, if the requested address does not belong to the resource service address, the source file is read directly from the hard disk and returned
"devServer": {
"publicPath": './dist'."port": 3000}Copy the code
There is one caveat here. One big difference between developing directly with Webpack and using webpack-dev-server is that the former generates Budnle.js each time, whereas webpack-dev-server just stores the packaging results in memory and does not write to the actual bundle.js. Each time webpack-dev-server receives a request, it simply returns the packed result in memory to the browser.
Another handy feature of Webpack-dev-server is live-reloading. When we change the content, we go to the browser and you see that the content in the browser has changed.
Webpack dev – server features:
- Have Webpack do module packaging and handle resource requests for the resulting packaging
- As a normal Web Server, it handles static resource file requests
- Solve the NPM run build back and forth, and then update the code problem, more convenient
- You can set the port port and open (to be automatic open the page), other more configuration can refer to the website api:webpack.js.org/configurati…
- Auto refresh: Content automatically changed by the browser