vue project using webpack dynamic configuration packing multiple domain environment

   Before and after the end of the separation now, various frameworks prevailing front-end sector, project packaging requirements have become more complex, share a vue project, depending on the command line, type the command, packing method different environment domain names. (Error correction welcome, thank you.)

1. Plug cross-env, npm install cross-env --save -dev, for configuring the command line command.

2. Modify package.json in the script command:

  Configuring the test (test), ready (pre-release), prod (official) three environments, npm run build defaults to npm run build: prod, but also according to their requirements, configuration more commands, custom parameters. Some people go online to see NODE_ENV modify this default parameter, configuration files, there are a lot of places have cited this parameter. I think that this can not change the default parameters, himself re-add a parameter on the line (here to add a BUILD_ENV parameter).

"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",
    "build": "npm run build:prod",
    "build:test": "cross-env NODE_ENV=production BUILD_ENV=test node build/build.js",
    "build:ready": "cross-env NODE_ENV=production BUILD_ENV=ready node build/build.js",
    "build:prod": "cross-env NODE_ENV=production BUILD_ENV=prod node build/build.js"
  },

 

3. Modify prod.env.js config directory

The default configuration which is this: Only one NODE_ENV

'use strict'
 
module.exports = {
  NODE_ENV: '"production"',  
}

 

After modifying the configuration:

'use strict'
const BUILD_ENV = process.env.BUILD_ENV
let baseUrl 
switch (BUILD_ENV) {
  case 'test':
    baseUrl = 'api.test.com'
    break;  
  case 'ready':
    baseUrl = 'api.ready.com'
   break ;
  case 'prod' :
    baseUrl = 'api.prod.com'
   break ;
}
module.exports = {
  NODE_ENV: '"production"', 
  BUILD_ENV: '"' + BUILD_ENV + '"',
  baseUrl: ' "' + baseUrl + '"' ,
}

  Modified configuration increases BUILD_ENV and baseUrl two attributes, attribute values remember splicing double quotes , process.env.BUILD_ENV BUILD_ENV value is entered in the command line, then make the appropriate determination in accordance BUILD_ENV. In the project, you can get prod.env.js exposed to the three attributes process.env. For example interface file, you need to dynamically modify process.env.baseUrl different environmental domain.

  

 

Guess you like

Origin www.cnblogs.com/c-ms/p/11073675.html