开发过程中,经常会有不同的生产环境配置的参数都是不一样的,使用webpack配置不同的参数环境
- 在config 目录下新建 文件
/*
* @param
* DEV_PORT 默认dev开发端口
* WEB_PATH_ASSETS 打包路径
* BASE_URL 接口前缀
*/
function getCodeEnv() {
const args = process.argv
var res
for (var i = 0; i < args.length; i++) {
if (args[i].indexOf('--env.CODE_ENV=') !== -1) {
res = args[i].split('=')[1] || ''
break
}
}
return res || 'production'
}
const CODE_ENV = `"${getCodeEnv()}"`
const { DEV_PORT, WEB_PATH_ASSETS, BASE_URL } = (() => {
const def = {
DEV_PORT: '80',
WEB_PATH_ASSETS: '"/dist/"',
BASE_URL: '""'
}
switch (CODE_ENV) {
case '"development"':
def.DEV_PORT = '3000'
def.WEB_PATH_ASSETS = '"/store-pass-portals/dist/"'
def.BASE_URL = '"/store-pass-portals"'
break
case '"test"':
def.DEV_PORT = '3000'
def.WEB_PATH_ASSETS = '"/store-pass-portals/dist/"'
def.BASE_URL = '"/store-pass-portals"'
break
case '"preproduction"':
def.DEV_PORT = '3000'
def.WEB_PATH_ASSETS = '"/dist/"'
def.BASE_URL = '""'
break
case '"production"':
default:
}
return def
})()
module.exports = {
CODE_ENV,
DEV_PORT,
WEB_PATH_ASSETS,
BASE_URL
}
- 修改dev.env.js 文件 添加 code.env.js
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
const codeEnv = require('./code.env') //
module.exports = merge(
prodEnv,
{
NODE_ENV: '"development"'
},
codeEnv
)
- 修改 config/index.js 文件 根据打包需要传递对应的参数
//这里只是代码片段 相应需要修改的
var path = require('path')
const codeEnv = require('./code.env')
module.exports = {
build: {
assetsPublicPath: JSON.parse(codeEnv.WEB_PATH_ASSETS), //对应的打包路径
....
},
dev:{
port: JSON.parse(codeEnv.DEV_PORT), //这里的端口don
}
- 修改prod.env.js
const merge = require('webpack-merge')
const codeEnv = require('./code.env')
module.exports = merge(
{
NODE_ENV: '"production"'
},
codeEnv
)
- index.html 如果需要手动引入静态资源路径
<link rel="icon" href="<%= process.env.WEB_PATH_ASSETS %>static/favorite.ico">
- package.json scripts修改
"dev": "node build/dev-server.js --env.CODE_ENV=development",
"dev_test": "node build/dev-server.js --env.CODE_ENV=test",
"dev_preprod": "node build/dev-server.js --env.CODE_ENV=preproduction",
"dev_prod": "node build/dev-server.js --env.CODE_ENV=production",
"build": "node build/build.js --env.CODE_ENV=production",
"build_test": "node build/build.js --env.CODE_ENV=test",
"build_preprod": "node build/build.js --env.CODE_ENV=preproduction",