webpack Vue条件编译

package.json

yarn add cross-env -D

1
2
3
4
"dev_test": "cross-env NODE_ENV=development TYPE=test webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"dev_pro": "cross-env NODE_ENV=development TYPE=pro webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"build_test": "cross-env NODE_ENV=production TYPE=test node build/build.js",
"build_pro": "cross-env NODE_ENV=production TYPE=pro node build/build.js"

build/webpack.dev.conf.js & webpack.prod.conf.js

1
2
3
4
5
6
7
8
9
var env;
if(process.env.TYPE=='test'){
env=require('../config/test.env')
}else{
env=require('../config/prod.env')
}
//'process.env': require('../config/dev.env')
// 改为
'process.env': env

config/index.js

1
2
3
4
5
6
// index: path.resolve(__dirname, '../dist/index.html'),
// 改为
index: path.resolve(__dirname, '../dist_'+process.env.TYPE+'/index.html'),
// assetsRoot: path.resolve(__dirname, '../dist'),
// 改为
assetsRoot: path.resolve(__dirname, '../dist_'+process.env.TYPE),

config/prod.env.js

1
2
3
4
5
module.exports = {
NODE_ENV: '"production"',
API: '"url"',
CLIENT: '"pro"'
}

config/test.env.js

1
2
3
4
5
module.exports = {
NODE_ENV: '"testing"',
API: '"url"',
CLIENT: '"test"'
}

使用

process.env.CLIENT