作用
WebpackDevServer作用:
0.运行一个服务器并运行与8080端口;
1.实现自动打包 ;(代替npx webpack
作用)
安装
yarn add webpack-dev-server
配置
webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
main: './src/index.js',
},
devServer: {
static: './dist' //webpack-dev-server配置,表示从哪个目录下面获取数据
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
cache: false
}),
new CleanWebpackPlugin(),
],
};
package.json:
"scripts": {
"watch": "webpack --watch",
"start": "webpack serve"
},
运行
运行命令:
yarn run start
WebpackDevServer实现请求转发
yarn add axios
更改配置:
devServer: {
static: './dist', //webpack-dev-server配置
proxy: {
'/users': {
target: 'https://api.github.com/',//如果有请求发送到/users这个路径,就转发到api.github.com
changeOrigin: true
}
}
},
源代码发生的变化:
axios.get('/users/defunkt').then(({data}) => {
console.log(data);
})
再重新启动一下:
yarn run start
怎样忽略以api为开头的接口中的api字符
proxy: {
'/api/users': {
target: 'https://api.github.com/',//如果有请求发送到/users这个路径,就转发到api.github.com
pathRewrite:{
'^/api':''
},
changeOrigin: true
}
}
再重新启动一下即可;
源代码见: https://github.com/richard1230/CodeLearning/tree/main/Javascript/Webpack/WebpackDevServer
原文始发于微信公众号(迪哥讲事):Webpack系列-WebpackDevServer
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论