# webpack-dev-server

开启服务器，可以做代理的功能很好用。

```javascript
cnpm install -D webpack-dev-server
```

**查看webapck-dev-server的配置参数，直接在命令行webpack-dev-server -h ,要想看别的依赖包（npm包），直接去npm查看详情：**[**https://www.npmjs.com/enterprise**](https://www.npmjs.com/enterprise)**。**

### **一些足够的配置：**

```javascript
const path = require("path");

const PATHS = {
    app:path.join(__dirname,"./src/index.js"),
    build:path.join(__dirname,"dist"),
    publicPath:"/"
};

const webpack = require("webpack");

module.exports=function(env,argv){
        return {
            entry: {
                main: PATHS.app,
            },
            mode: "development",
            output: {
                path: PATHS.build,
                filename: '[name].boundle.js',
                publicPath:PATHS.publicPath,
            },
            devServer: {
                    historyApiFallback: true,
                    contentBase:path.resolve(__dirname,'dist'),
                    quiet: false, //控制台中不输出打包的信息
                    noInfo: false,
                    inline: true, //开启页面自动刷新,
                    hot:true,
                    publicPath:PATHS.publicPath,
                    stats:'errors-only',
                    lazy: false, //不启动懒加载
                    compress:true,//开启后端gzip
                    progress: false, //显示打包的进度
                    overlay:{  //把编译的错误显示在浏览器上
                        errors:true,
                        warnings:true,
                    },
                    watchOptions: {
                        aggregateTimeout: 300
                    },
                    port: '8099', //设置端口号
                    //其实很简单的，只要配置这个参数就可以了
                    proxy: {
                        '/INFManage': {
                            target: 'http://localhost:8080',
                            secure: false,
                            changeOrigin:true,
                        }
                    }
                    },
                plugins:[
                      //热更新替换，写插件，就要在运行的node命令加 --hot
                      new webpack.HotModuleReplacementPlugin(),
                      new webpack.NamedModulesPlugin(),//显示模块的名字，默认是显示模块id
                ],
        };
}
```

根据实验，现在我能做的真正的模块热更新是根据这篇文章的配置：<http://www.cnblogs.com/stoneniqiu/p/6496425.html>。

明白了，module.hot.accept(),的用法，具体该怎样实现模块额热替换。先看package.json，怎样启动服务和热更新配置。一般都是在开发环境用，所以在生产环境不要使用热更新插件，以免增加不必要的代码，而且完全没有用。

```javascript
// package.json
{
  "name": "html5",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "server": "webpack-dev-server  --inline --env development -w", // --inline 使用热更新
    "build": "webpack --env production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^2.28.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }
}
```

把主要的代码放在componet.js,改变这个模块的js内容，让浏览器不刷新但是用最新的js文件css文件，

```javascript
// component.js
console.log(445);

export function create(str="webttapck"){


    const ele  = document.createElement("div");

        ele.innerHTML = "erttryffd" ;

        return ele ; 
};

// index.js

import {create} from './component';

let demoComponent=create();
document.body.appendChild(demoComponent);

//HMR 热更新接口
console.log(454545);// 当我改变这个index.js文件，浏览器会刷新，不是改变额引用模块

if(module.hot){
// HMR引用的是 component.js这个模块，只要component.js文件发生改变，就会使用替换旧的模块使用新的。

    module.hot.accept("./component",()=>{ 


        console.log("hot");
        const nextComponent=create();
        document.body.replaceChild(nextComponent,demoComponent);
        demoComponent=nextComponent;
    })
}
//注意，
```

这样确实做到模块的热更新，可是得使用webpack-dev-server^2.4.1 ,"webpack":"^2.2.1"，使用最新的版&#x672C;**<webpacj@4.6.x>搭配webpack-dev-server\@3.1.4**却不行了。我已经把配置变得一样，可最新的版本还是不行。连续搞这没看热更新3天，只要是放在最新webpack4，就是不行，也不报错。就是HMR不工作，怎么看出来的呢？就是启动服务后，修改js文件后，浏览器的控制台只是输出WDS信息，根本没有HMR check server 更新新的模块。也就是根本没有调用 module.hot.accept(),这个方法。

差了很多文章，有的说在入口entry 加上 热更新额路径

```javascript
entry:{
    app:["webpack-dev-server/client?http://localhost:8080/","./src/index.js"]
}
```

**然而并没有什么用，有人说这是用nodejs启动服务，不用webpack-dev-server启动时才要加。网上一大堆讲热更新的，方法都是差不多，也就那几个配置， --hot。--inline。配置方面我是真找不出原因了，目前<webpacj@4.6.x>搭配webpack-dev-server\@3.1.4。然而<webapck@2.x> 搭配<webpack-dev-server@2.X>可以没问题。那就换升级版本。直接 cnpm i -D webpack 不能更新，说是已经安装了。那就用 cnpm i -D <webpack@3.x> , 3.x配2.x的server 也没问题。换成webpack4.x 得安装webapck-cli ，不然报错，而且4.x搭配webpack-dev-server2.x会报错，最后变成webpack4..8.x 搭配 webpack-dev-server3.x，都是最新的版本。发现之前的配置可以热更新了。对比了发现，之前使用webpack4.6.X ，原来得用webpack4.8.x。以后一定的记得一用最新额版本就都用最新的。并且注意各个版本的依赖包要用对应正确版本。**

**码云地址地址demo :**[**https://gitee.com/sekin/webapck-hot**](https://gitee.com/sekin/webapck-hot)

还有一种使用nodemon 同时监听前端和后端的代码改变，实现无刷新更新，

## 注意当使用babel转化js时，要是使用了编译环境loader :babel-preset-env,默认是将ES6模块编译成CommonJs模块，这样会导致模块热更新HMR使用不了，可以配置配置{modules:false}，则不会编译模块类型。

```javascript
//.babelrc
{
    "presets": [
        [
            "env",
        // 不编译ES6模块    可选 ："amd" | "umd" | "systemjs" | "commonjs" | false, 
        //   defaults to "commonjs". 
            {"modules":false} 
        ],
         "react"
    ],
    "plugins":[
        "transform-runtime"
    ]
}
```

## React保留上次的状态的热更新。

**详解地址：**[**https://www.jianshu.com/p/bcad129a1c69**](https://www.jianshu.com/p/bcad129a1c69)

更多关于webpack-dev-server的配置可以看<https://github.com/huruji/blog/issues/10>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sekin.gitbook.io/myjs/webpack/webpack-dev-server.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
