npm i -D webpack-dev-server
webpack-dev-server是webpack官方提供的一个小型Express服务器。
使用它可以为webpack打包生成的资源文件提供web服务。
webpack-dev-server文档
新增插件方面配置
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
// 入口文件 默认值是 ./src/index.js
entry: "./src/index.js",
// 打包后的出口文件 默认值是 ./dist/main.js
output: {
// 输出的文件名称
filename: 'main.js',
},
// 使用开发模式打包 development, production 或 none
mode: "development",
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
// 移动/src/index.html到/public/index.html
template: './public/index.html',
// inject:是否在template文件中插入打包的js文件
inject: true,
title: 'webpack is good',
chunks: ['main']
})
],
devServer: {
port: 8800,
open: true,
static: {
directory: path.join(__dirname, 'public'),
},
compress: false
}
}
package.json文件变化,修改了dev执行命令,使用webpack-dev-server
代替 webpack
执行 npm run dev
命令后不再生成/dist/*
文件,生成的文件都放入内存中。
{
"name": "webpack-demo003-webpack-dev-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development --open",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^5.5.3",
"webpack": "^5.87.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
}
# > npm run dev
> [email protected] dev D:\my-workspace\前端代码\learn-webpack003\webpack-demo003-webpack-dev-server
> webpack-dev-server --mode development --open
<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:8800/
<i> [webpack-dev-server] On Your Network (IPv4): http://172.26.142.2:8800/
<i> [webpack-dev-server] Content not from webpack is served from 'D:\my-workspace\前端代码\learn-webpack003\webpack-demo003-webpack-dev-server\public' directory
asset main.js 266 KiB [emitted] (name: main)
asset index.html 248 bytes [emitted]
runtime modules 27.4 KiB 12 modules
webpack-dev-server文档
在服务器已经启动后打开浏览器。设置其为 true 以打开你的默认浏览器
devServer: {
open: true,
}
在浏览器中打开多个指定页面
devServer: {
open: ['/my-page', '/another-page'],
}
devServer: {
port: 8080,
}
当拥有单独的 API 后端开发服务器并且希望在同一域上发送 API 请求时,代理某些 URL 可能会很有用。
现在,对 /api/users 的请求会将请求代理到 http://localhost:3000/api/users。
devServer: {
proxy: {
'/api': 'http://localhost:3000',
},
}
如果不希望传递/api,则需要重写路径:
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: { '^/api': '' },
},
},
},
如果想将多个特定路径代理到同一目标
可以使用一个或多个带有 context 属性的对象的数组:
devServer: {
proxy: [
{
context: ['/auth', '/api'],
target: 'http://localhost:3000',
},
]
},
支持https的后端服务器
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
secure: true,
},
},
},