Use webpack-dev-server to build a local server

webpack provides an optional local development server webpack-dev-server. This local server is based on node.js and uses the express framework internally, which can achieve what we want to let the browser automatically refresh and display our modified results.

The first step: installation

It is a separate module and needs to be installed before use.

installation:npm install --save-dev [email protected]

The webpack version I use is 3.6.0, and the webpack-dev-server version is 2.9.0

Step 2: Configure

After installing we need to add in webpack.config.js file dev-serverconfiguration.

The option itself can set the following attributes:

  • contentBase : Which folder provides local service for, here I fill in./dist
  • port : port number, the default is 8080
  • inline : Control whether the page refreshes in real time. The value is true or false. When it is true, the page will refresh automatically after modifying the code
  • historyApiFallback : In the SPA page, rely on the history mode of HTML5
// webpack.config.js
//...

module.exports = {
    
    
   // ...其它配置
  devServer: {
    
     
    contentBase:'./dist',
    inline:true,
  }
}

Step 3: Use

At this point, if we enter directly in the terminal webpack-dev-servercommand, I found incorrect report: Tell us find this command.
Insert picture description here
Reason : No matter whether we enter the command directly through cmd or the terminal of the editor, it will look for the command in the global to execute it, just like the above. But webpack-dev-server is installed locally (because we use --save-devit instead -g), so if it can't be found globally, an error will be reported.

Solution : In the package.jsonscripts file, add a command:

//package.json文件

"scripts": {
    
    
    // ...其它命令
    "dev": "webpack-dev-server --open" //--open表示执行完命令后自动打开浏览器
}

We then use the npm run devcommand on it

Explain the commands in scripts:

  • are some of the command scripts defined when we use npm run xxxtime, will go to package.json file scripts to find xxx command to execute. Next, we will find the corresponding position of the command in a certain order.
  • First, will the local node_modules/.binfind the corresponding command path. If it is not found, it will look for it in the global environment variables.

Precautions

Insert picture description here
There is no dist folder in my code directory structure, and I cannot see the compiled files, but the webpack-dev-server can run normally after starting the webpack-dev-server. The reason is that the real-time compiled files are saved in the memory.

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/112722600