Home  >  Article  >  Web Front-end  >  How to use Npm run build in vue to pass different parameters according to the environment

How to use Npm run build in vue to pass different parameters according to the environment

php中世界最好的语言
php中世界最好的语言Original
2018-05-26 11:32:485130browse

This time I will show you how to use Npm run build in vue to pass different parameters according to the environment, and use Npm run build in vue to pass different parameters according to the environment. What are the precautions?. Here are the actual cases. Let’s take a look.

During project development, the front-end is very troubled when configuring the back-end api domain name. It often appears:

Local development environment: api-dev.demo.com

Test environment: api-test.demo.com

Online production environment: api.demo.com,

This time it is packaged in the Vue.js project, and I will teach you how to do it:

Use npm run build -- xxx , according to the passed parameter xxx to determine different environments and give different domain name configurations.

1. Modification of /config/dev.env.js in the project:

New addition: HOST: '"dev"'

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
 NODE_ENV: '"development"',
 HOST: '"dev"'
})

2. Modify /config/prod.env.js in the project:

Get the parameters passed in:

'use strict'
let HOST = process.argv.splice(2)[0] || 'prod';
console.log(HOST);
module.exports = {
 NODE_ENV: '"production"',
 HOST: '"'+HOST+'"'
}

3. Project Modify the ajax package:

/**
** 设置API接口域名
**/
let apiUrl = '';
// 根据 process.env.HOST 的值判断当前是什么环境
// 命令:npm run build -- test ,process.env.HOST就设置为:'test'
let HOST = process.env.HOST;
HOST = HOST === 'prod' ? '' : '-' + HOST;
apiUrl = 'http://api'+HOST+'.demo.com';
axios.defaults.baseURL = apiUrl;

4. Finally type the command:

npm run build -- test

Note – it is two horizontal bars, followed by parameters, so that process.env.HOST will get the parameter 'test',

apiUrl = 'http://api-test.demo.com'

If the online prod is released and packaged, npm run build -- prod

apiUrl = 'http://api.demo.com'

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the underlying logic of new() in JS

How to use Koa2 file upload and download

The above is the detailed content of How to use Npm run build in vue to pass different parameters according to the environment. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn