安装(有全局和局部):
npm install webpack-dev-server —save
webpack.config.js:
const webpack = require('webpack')
const extractTextCss = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports={
mode:'production',
entry:{
app:'./src/app.js',
},
output:{
path:__dirname+"/dist",
filename:'[name].bundle.js'
},
module:{
rules:[
{
test:/\.less$/,
use:extractTextCss.extract({
fallback:{
loader:'style-loader',
options:{
//insertInto:"#mydiv",
singleton:true,
//transform:"./transform.js"
}
},
use:[
{
loader:'css-loader',
options:{
modules:{
localIdentName:'[path][name]_[local]_[hash:4]'
}
}
},
{
loader:'less-loader'
}
]
})
}
]
},
devtool:'eval-source-map',
devServer:{
port: 9001,
inline:true,
overlay:true,
hot:true,
hotOnly:true,
historyApiFallback:{
rewrites:[
{
from:/^\/([ -~]+)/,
to:function(context){
return './'+context.match[1]+'.html'
}
}
]
},
proxy:{
"/smartSpec":{
target:"https://mooc.study.163.com/",
changeOrigin:true,
pathRewrite:{
"^/smartSpec/qd":"/smartSpec/detail/1202816603.htm"
},
},
}
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
minify: {
collapseWhitespace: true
},
inject:true,
}),
new extractTextCss({
filename:"app.bundle.css",
disable:true
}),
]
}
package.json:
配置了一个命令dev,运行的是局部webpack-dev-server。
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open"
}
inline: 会在页面最上面显示一个状态信息,默认值是true不显示,如果置为false则出现。
overlay: 会将错误显示在页面(true),而不是控制台上。
historyApiFallback: true,发现找不到路径,则停留在原页面。
from,to 重定向。
historyApiFallback:{
rewrites:[
{
from:/^\/([ -~]+)/,
to:function(context){
return './'+context.match[1]+'.html'
}
}
]
}
app.js:
import test from "./test.less";
import test2 from "./test2.less";
import $ from 'jquery';
$.ajax({
url:"/smartSpec/qd",
type:'get',
success:function(res){
console.log(res);
}
});
var i=0;
document.getElementById('mydiv').setAttribute('class',test2.div1);
console.log(j.a);
如果不使用代理的话,会出现跨域错误问题。
changeOrigin默认是false:请求头中host仍然是浏览器发送过来的host。如果设置成true:发送请求头中host会设置成target。
proxy:{
"/smartSpec":{
target:"https://mooc.study.163.com/",
changeOrigin:true,
pathRewrite:{
"^/smartSpec/qd":"/smartSpec/detail/1202816603.htm"
},
},
}
热更新:
如果不配置热更新,更新代码的时候,会刷新页面,也就是live loading。
extract-text-webpack-plugin 和热更新并兼容,所以要设置disable:
new extractTextCss({
filename:"app.bundle.css",
disable:true
})
在app.js中设置一个定时器:
var i = 0;
setInterval(function(){
i++;
document.getElementById("mydiv").innerHTML = i;
});
在webpack.config.js文件中也设置了
{
hot: true,
hotOnly: true
}
当我们更改app.js文件的时候,发现页面刷新了。这是因为我们还需要在app文件中写入,判断module是否有hot模块,如果有则accept。
if(module.hot){
module.hot.accept();
}
经过上面的更改,在修改定时器,会发现页面并无在刷新,而页面上会出现两个计时器,一个是改之前,一个是改之后的,两个计时器间隔显示。