Nuxt.js distinguishes the configuration of the production environment and the development environment, directly accessed through process.env.xxx
- download cross-env
npm install --save-dev cross-env
- Create a new folder env.js under the root directory
module.exports = {
development: {
NODE_ENV: 'development',
VUE_APP_BASE_API: '/dev',
},
production: {
NODE_ENV: 'production',
VUE_APP_BASE_API: '/pro',
},
}
- Add the following code in nuxt.config.js
import env from './env'
export default {
... ...
env:{
NODE_ENV: env[process.env.NODE_ENV].NODE_ENV,
VUE_APP_BASE_API: env[process.env.NODE_ENV].VUE_APP_BASE_API,
},
... ...
}
- Modify the startup configuration in package.json to:
{
"scripts": {
"dev": "cross-env NODE_ENV=development nuxt",
"build": "cross-env NODE_ENV=production nuxt build",
... ...
},
}
- used in the project
console.log(process.env.VUE_APP_BASE_API)
console.log(process.env.VUE_APP_BASE_API)