新建 .env.development和 .env.production
2. .env.development文件內容
# just a flag
ENV = 'development' //開發模式
# base api
VUE_APP_BASE_API = '/dev-api' //------------->可以通過process.evn.xxx訪問
# vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable,
# to control whether the babel-plugin-dynamic-import-node plugin is enabled.
# It only does one thing by converting all import() to require().
# This configuration can significantly increase the speed of hot updates,
# when you have a large number of pages.
# Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js
VUE_CLI_BABEL_TRANSPILE_MODULES = true
.env.production文件內容
# just a flag
ENV = 'production'
# base api
VUE_APP_BASE_API = ''
# vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable,
# to control whether the babel-plugin-dynamic-import-node plugin is enabled.
# It only does one thing by converting all import() to require().
# This configuration can significantly increase the speed of hot updates,
# when you have a large number of pages.
# Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js
VUE_CLI_BABEL_TRANSPILE_MODULES = true
3.在程序中如何訪問
例如,create一個axios對象,並且baseURL爲(步驟2)中兩個文件設置的VUE_APP_BASE_API。
開發環境下VUE_APP_BASE_API==='/dev-api',生成環境下VUE_APP_BASE_API===''
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 60000, // request timeout
withCredentials: true, // 攜帶cookie
crossDoMain: true // 跨域
})
4.開發模式下,vue中的代理,跨域
pathRewrite下,^/dev-api 的值,必須等於VUE_APP_BASE_API。注:^ 表示已某某開頭
module.exports = {
devServer: {
port: 8080,
proxy: {
'/dev-api': {
// target: 'http://118.25.139.110:8088/', // target host
target: 'http://api.thdtek.com', // target host
// target: 'http://192.168.1.211:8080/', // target host
ws: true, // proxy websockets
changeOrigin: true, // needed for virtual hosted sites
pathRewrite: {
'^/dev-api': '' // rewrite path //---------------------->重寫的路徑值
}
}
}
},
}