This example tutorial is based on the project created by VUE-CLI 2.0. Suitable for situations where the current project has multiple API base addresses. Not applicable to the latest VUE-CLI 3.0, vue-CLI 3.0 implementation will be simpler and easier to understand.
1. Installcross-env
cnpm install --save-dev cross-env
Copy the code
2. Modify the package.json configuration
Add env_config=prod and env_config=dev respectively to control the current compression environment
package.json
"scripts": {
- "build": "node build/build.js",
+ "build:prod": "cross-env env_config=prod node build/build.js",
+ "build:dev": "cross-env env_config=dev node build/build.js"
}
Copy the code
3. Create an interface configuration file
We will create a new file, apiurl.js, under the SRC folder, to configure the interface address.
src/apiUrl.js
const master = {
api1: 'http://pro1.com/'.api2: 'http://pro2.com/'};const dev = {
api1: 'http://prodev1.com/'.api2: 'http://prodev2.com/'};// If there are others, you can customize them, but remember to export them.
module.exports = { master, dev };
Copy the code
4. Modify the Webapck configuration
Test the configuration file locallybulid/webpack.dev.conf.jsModify the
// ...
+ const api = require('.. /src/apiUrl');
+ const env = require('.. /config/dev.env');
+ env.api = "'" + JSON.stringify(api.dev) + "'";
// ...
// ...
new webpack.DefinePlugin({
- 'process.env': require('.. /config/dev.env')
+ 'process.env': env
}),
// ...
Copy the code
Online compression package configuration filebuild/webpack.prod.conf.jsModify the
// ...
const env = process.env.NODE_ENV === 'testing'? require('.. /config/test.env') : require('.. /config/prod.env')+ const api = require('.. /src/apiUrl');
+ if(process.env.env_config === 'prod') {
+ env.api = "'" + JSON.stringify(api.master) + "'";
+ } else if(process.env.env_config === 'dev') {
+ env.api = "'" + JSON.stringify(api.dev) + "'";
+}
// ...
Copy the code
5. Obtain the address of the interface
src/api.js
// ...
// API interface address, all subsequent interface addresses can be found in the API.
let api;
api = JSON.parse(process.env.api);
// ...
Copy the code
6. Press the packet
- Packing in production environment
npm run build:prod Copy the code
- Test the environment
npm run build:dev Copy the code
- Local test
npm run dev Copy the code