在新建好的項目中,通常執行npm run build就是打包了,但此時只能打包到一個環境,不一樣環境須要配置不一樣的地址,能夠手動更改接口的地址,也能夠自行配置命令而不須要每次打包進行地址切換,步驟以下:
文件結構以下圖:
html
1)在config文件內新建test.env.js文件:vue
'use strict' module.exports = { NODE_ENV: '"testing"', ENV_CONFIG:'"test"' }
2)修改config內的prod.env.js文件:node
'use strict' module.exports = { NODE_ENV: '"production"', ENV_CONFIG:'"prod"' }
3)對build中webpack.prod.conf.js作以下修改:webpack
// const env = require('../config/prod.env') //原始代碼
或者爲web
// const env = process.env.NODE_ENV === 'testing' //原始代碼 // ? require('../config/test.env') // : require('../config/prod.env') // console.log(process.env.NODE_ENV);
修改成:npm
const env = config.build[process.env.env_config+'Env']
4)config中的index.js 文件中build部分代碼修改以下:json
build: { prodEnv: require('./prod.env'), testEnv: require('./test.env'), // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // ····餘下的代碼就不寫了 }
5)確認安裝cross-envwebpack-dev-server
npm install cross-env –save-dev
6)對build文件夾下的build.js的修改:ui
'use strict' require('./check-versions')() // process.env.NODE_ENV = 'production' //註釋掉 const ora = require('ora') const rm = require('rimraf') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') const webpackConfig = require('./webpack.prod.conf') // const spinner = ora('building for production...') //註釋掉 var spinner = ora('building for ' + process.env.NODE_ENV + ' of ' + process.env.env_config+ ' mode...' ) spinner.start()
7)修改package.json文件(在script裏面添加):spa
"scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", "unit": "jest --config test/unit/jest.conf.js --coverage", "e2e": "node test/e2e/runner.js", "test": "npm run unit && npm run e2e", "lint": "eslint --ext .js,.vue src test/unit test/e2e/specs", "build": "node build/build.js", "build--test": "cross-env NODE_ENV=testing env_config=test node build/build.js", "build--prod": "cross-env NODE_ENV=production env_config=prod node build/build.js" },
8)在common文件下新建env.js,對環境進行判斷並切換,內容以下:
/* * 配置編譯環境和線上環境之間的切換 * baseUrl: 域名地址 * routerMode: 路由模式 */ let baseUrl = ''; let routerMode = 'history'; let DEBUG = false; let cancleHTTP = [];//取消請求頭設置; //注:下面的baseUrl地址爲假地址,只是模擬的,沒法調通。 if (process.env.NODE_ENV == 'development') { baseUrl = "https://10.248.65.100/GetTravelMethod"; DEBUG = true; }else if(process.env.NODE_ENV == 'production'){ baseUrl = "https://10.248.65.200/GetTravelMethod"; DEBUG = false; }else if(process.env.NODE_ENV == 'testing'){ baseUrl = "https://10.248.65.150/GetTravelMethod"; DEBUG = false; } export{ baseUrl, routerMode, DEBUG, ROLE, cancleHTTP }
想要test環境下則運行:
npm run build--test
相應的改成production環境則運行:
npm run build--prod