1、安装webpack-dev-server
cnpm install webpack-dev-server -D
2、package.js同级目录下新建package.config.js文件。代码如下:
module.exports={
entry:'',
output:'',
devServer:{
port:9999,
host:'localhost'
}
}
3、package.json文件
{
...,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev":"webpack-dev-server"
},
...,
}
本文已经定义过process
大致配置:webpack.config.js
// 环境变量
const env = require('yargs').argv.env
console.log(env);
const serverInfo = {
apiUrl: 'https://mp.csdn.net/',
websockUrl: 'https://mp.csdn.net/'
}
if (env == 'prod') {
serverInfo.apiUrl = 'https://mp.csdn.net/'
serverInfo.websockUrl = 'https://mp.csdn.net/'
}
...
plugins: [
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
process:{
env: {
serverInfo: JSON.stringify(serverInfo)
}}
}),
]
在index.js中可直接使用 const wsHost = process.env.serverInfo.websockUrl;访问
4、process 环境变量未定义报错
在项目过程中出现一个问题,添加webpack-dev-server中代理服务成功,但process变量取不到
处理方式:添加html-webpack-plugin
安装html-webpack-plugin,
npm i --save-dev html-webpack-plugin
附地址npm链接https://www.npmjs.com/package/html-webpack-plugin
在webpack.config.js引入html-webpack-plugin
const HtmlPlugin = require('html-webpack-plugin');
...
plugins: [
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
process:{
env: {
serverInfo: JSON.stringify(serverInfo)
}}
}),
new CleanPlugin(['build']),
new CopyPlugin([{
from: path.resolve(__dirname, 'js'),
to: path.resolve(__dirname, 'build/js')
}, {
from: path.resolve(__dirname, 'css'),
to: path.resolve(__dirname, 'build/css')
}]),
// 增加如下代码段
new HtmlPlugin({
template: './index.html',
})
]
package.json文件配置
...
"scripts": {
"build:test": "webpack --config ./webpack.config.js --progress --color --env test ",
"build:pre": "webpack --config ./webpack.config.js --progress --color --env pre",
"build:prod": "webpack --config ./webpack.config.js --progress --color --env prod",
"dev": "webpack-dev-server --config ./webpack.config.js --hot --env test"
},
...
启动服务:npm run dev
访问:http://localhost:9999/ 即可调试
附:webpage遇到一个警告⚠️
1)The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment. You can also set it to 'none' to disable any default behavior
查了下需要配置
"scripts": {
"start": " --mode development",
"build": "--mode production",
}
修改配置dev
...
"scripts": {
"build:test": "webpack --config ./webpack.config.js --progress --color --env test ",
"build:pre": "webpack --config ./webpack.config.js --progress --color --env pre",
"build:prod": "webpack --config ./webpack.config.js --progress --color --env prod",
"dev": "webpack-dev-server --config ./webpack.config.js --mode development --hot --env test"
},
...
完。