Vue设置不同的环境发布程序

原文地址:

http://www.cnblogs.com/JimmyBright/p/7307486.html

通常应用程序上线都会经过开发环境、测试环境、生产环境三个阶段,三个环境通常会对应有三个不同的后端api地址或者其他的配置项。下面主要记录怎么把不同的配置项发布到不同的运行环境里边。

打开vue项目找到config目录,vue-cli生成的项目下有 dev.env.js index.js prod.env.js test.env.js四个文件

假设三个环境对应三个不同的接口访问的url前缀。

 在需要访问接口地址的地方

alert(process.env.Host_url)

这样还并不能取到不同环境下的Host_url
点开config下的index.js
 1 // see http://vuejs-templates.github.io/webpack for documentation.
 2 var path = require('path')
 3 module.exports = {
 4   build: {
 5     env: require('./prod.env'),
 6     index: path.resolve(__dirname, '../dist/index.html'),
 7     assetsRoot: path.resolve(__dirname, '../dist'),
 8     assetsSubDirectory: 'static',
 9     assetsPublicPath: '/',
10     productionSourceMap: true,
11     // Gzip off by default as many popular static hosts such as
12     // Surge or Netlify already gzip all static assets for you.
13     // Before setting to `true`, make sure to:
14     // npm install --save-dev compression-webpack-plugin
15     productionGzip: false,
16     productionGzipExtensions: ['js', 'css'],
17     // Run the build command with an extra argument to
18     // View the bundle analyzer report after build finishes:
19     // `npm run build --report`
20     // Set to `true` or `false` to always turn it on or off
21     bundleAnalyzerReport: process.env.npm_config_report
22   },
23   dev: {
24     env: require('./dev.env'),
25     port: 8080,
26     autoOpenBrowser: true,
27     assetsSubDirectory: 'static',
28     assetsPublicPath: '/',
29     proxyTable: {},
30     // CSS Sourcemaps off by default because relative paths are "buggy"
31     // with this option, according to the CSS-Loader README
32     // (https://github.com/webpack/css-loader#sourcemaps)
33     // In our experience, they generally work as expected,
34     // just be aware of this issue when enabling this option.
35     cssSourceMap: false
36   }
37 }

修改第五行就可以了。

例如将项目发布到开发环境,第五行改成

 env: require('./dev.env'),
然后在控制台执行:npm run build
dist下面的项目发布之后就能取到开发环境的url
同理:
在测试环境发布,就需要将第五行改成
 env: require('./test.env'),
执行:npm run build
在生产环境发布就需要将第五行改成:
env: require('./prod.env'),
执行:npm run build

至于为什么这样改就可以了,需要稍微理解一下代码的执行顺序就明白了。O(∩_∩)O
 
原文地址:https://www.cnblogs.com/JimmyBright/p/7307486.html