在没有用devServer之前我们都是打包之后,通过文件的方式运行index.html文件,并且每改变一次代码都要重新打包,这样不仅不可以发送ajax请求而且会使得我们的开发效率极其低下.
那么我们可以通过devserver在本地运行一个node环境,通过http的形式访问index.html文件并保持实时更新.
watch
在package.json中配置 "serve":"webpack --watch"
//完整代码:
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve":"webpack --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.1.0",
"file-loader": "^4.1.0",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.12.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.37.0",
"webpack-cli": "^3.3.6"
}
}
通过这种方式可以实现不用重复打包,但打包的项目还是以文件的形式运行不可以发送ajax请求.不推荐使用
devServer
配置webpack.config.js中添加
devServer:{
contentBase:'./dist',
open:true,
port:8000
}
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const {CleanWebpackPlugin}= require('clean-webpack-plugin');
module.exports={
mode:'development',
devtool:'source-map',
entry:{
main:'./index.js'
},
devServer:{
contentBase:'./dist',
open:true,
port:8080
},
module:{
rules:[
{
test:/\.jpg$/,
use:{
loader:'file-loader',
options:{
outputPath:'images',
name:'img.jpg'
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
}
]
},
output:{
path:path.resolve(__dirname,'./dist'),
filename:'index_bundle.js'
},
plugins:[new HtmlWebpackPlugin({
template:'./index.html'
}),new CleanWebpackPlugin()]
}
配置package.json
"start":"webpack-dev-server"
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve":"webpack --watch",
"start":"webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.1.0",
"file-loader": "^4.1.0",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.12.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.37.0",
"webpack-cli": "^3.3.6"
}
}
安装webpack-dev-server
npm install webpack-dev-server
运行:npm run start即可.