Note the use of webpack-dev-server.
First, let’s look at the basic webpack.config.js notation
module.exports = {
entry: './src/js/index.js',
output: {
path: './dist/js',
filename: 'bundle.js'
}
}Copy the code
The configuration file provides an entry and an exit from which WebPack packs and compiles JS. Although Webpack provides the webpack –watch command to dynamically monitor file changes and package them in real time, and output new bundle.js files, the packaging speed will be slow when there are too many files. Besides, this packaging method cannot be hot replace, that is, after every Webpack compilation, You’ll also need to manually refresh the browser.
Some of the features of Webpack-dev-server overcome these two problems. Webpack-dev-server basically starts an Http server that uses Express. Its main function is to serve resource files. In addition, the Http server and client use the WebSocket communication protocol. After the original file is changed, webpack-dev-server will compile in real time, but the last compiled file is not output to the destination folder, which is configured as above:
output: {
path: './dist/js',
filename: 'bundle.js'
}Copy the code
Note: after you start webpack-dev-server, you will not see the compiled files in the target folder, the real-time compiled files are saved in memory. Therefore, many students will not see the compiled files when they use webpack-dev-server for development
How to use webpack dev-server:
Start the
There are two ways to start webpack-dev-server:
configuration
I’m going to focus on the form of the CMD line, the Node.js API and take a look at the official documentation. It can be started from NPM script. My directory structure is:
app
|__dist
| |__styles
| |__js
| |__bundle.js
| |__index.html
|__src
| |__styles
| |__js
| |__index.js
|__node_modules
|__package.json
|__webpack.config.jsCopy the code
content-base
Set directory for webpack-dev-server server. If not specified, the default is in the current directory.
webpack-dev-server --content-base ./dist
Copy the code
It is also important to note that if the output publicPath is configured in webpack.config.js, it should be adjusted in index.html. Because the webpack-dev-server file is relative to the publicPath path. So, if your webpack.config.js configuration looks like this:
Module. exports = {entry: './ SRC /js/index.js', output: {path: './dist/js', filename: 'bundle.js', publicPath: '/assets/' } }Copy the code
Now, the paths introduced in the index.html file have changed accordingly:
Demo
Copy the code