关于webpack dev server,看官网上的介绍 :
Use webpack with a development server that provides live reloading. This should be used for development only.
It uses webpack-dev-middleware under the hood, which provides fast in-memory access to the webpack assets.
两个关键词:
- live reloading
- development only
先通过npm安装:
npm install webpack-dev-server --save-dev
完成后,是当前最新版本:
"webpack-dev-server": "^2.9.4"
再把package.json中的script对象中的”dev”值改为:
"scripts": {
"dev": "webpack-dev-server",
"prot": "webpack -d"
},
然后运行localhost:8080,就可以看到和通过path访问是一样的结果:
当更改app.scss文件中的p的color 为yellow时,页面会自动刷新:
那么"dev": "webpack-dev-server"
与"dev": "webpack -d"
其中的一点区别就是后者把文件渲染并写到磁盘上,而运行前者时,文件是来自于内存中,为了验证这一点,现在把dist目录下的文件删除掉,而后页面仍能显示出来,而如果是code like "dev": "webpack -d"
,页面就什么都没有显示。
"dev": "webpack -d"
将dist目录下的文件删除后,显示页面是:
而运行
"dev": "webpack-dev-server"
显示页面仍然是正常的:
关于config webpack dev server :
https://webpack.js.org/configuration/dev-server/
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true, //gzip
port: 9000,
stats: "errors-only", //only show the error message in terminal
open: true //will open a new browser widow when the dev server for the the first sound
}
记得声明path,不然contentBase中的path会因找不到而报错:
var path = require("path");