Cooperate with webpack and webpack-dev-server processing
- installation
// 安装
cnpm html-webpack-plugin --save -D
cnpm install webpack webpack-cli webpack-dev-server --save -D
- New src folder New files index.html and index.js
- Send a request in index.js
import axios from 'axios'
axios.get('http://127.0.0.1:3001/user').then(result=>{
console.log(result)
})
- New
webpack.config.js
and configure
// 配置webpack.config.js
var path = require('path') // 绝对路径
const HtmlWebpackPlugin = require('html-webpack-plugin');// 打包html的插件
module.exports = {
mode:'development',
// 入口文件
entry: './src/index.js',
// 出口文件
output: {
path:path.resolve(__dirname, 'build'), // 输出文件的存放路径
filename: "bundle.js", //输出文件的名称
},
devServer:{
port:3000,
progress:true,
contentBase:'./build',
},
plugins:[ // html产出插件的应用
new HtmlWebpackPlugin({
template:'./src/index.html',
filename: 'index.html'
})
]
}
- Create a new server.js service and write a user interface in it
let express = require('express')
let app = express()
app.get('/user',(req,res)=>{
res.json({name:'jack'})
})
app.listen(3001,function(){
console.log("server is running 3001")
})
-
In
package.json
thescripts
next configuration
"dev": "webpack-dev-server --open --host 127.0.0.1 --port 3000"
so packed when completed will automatically open port 3000 window -
Start server.js service
node server
click the plus sign to open a new terminal drop-down box to switch terminal
-
Switching input terminal
npm run dev
to package Packaging Success 3000 will automatically open the window
this time will see the console error
solve…:
In the webpack.config.js
configuration proxy
as follows
proxy:{ //代理过滤 处理跨域
'/':{
// 意思所有这个地址的请求都以 / 发送到 http://localhost:3001下
target:'http://localhost:3001',
changeOrigin:true // 改变源
}
}
After repacking, you
npm run dev
will see some quick links to the data
:
Webpack packaging and configuration