Nuxt 多环境静态打包

3,524 阅读1分钟

一、nuxt.config.js文件中定义一个环境变量environment

env: {
    environment: process.env.environment
}

二、package.josn中配置对应环境的打包命令

"scripts": {
    "dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
    "build": "nuxt build",
    "start": "cross-env NODE_ENV=production node server/index.js",
    // 以下就是根据多个环境静态打包命令
    "generate": "cross-env environment=production nuxt generate",
    "generate:dev": "cross-env environment=development nuxt generate",
    "generate:test": "cross-env environment=test nuxt generate",
    "generate:pre": "cross-env environment=presentation nuxt generate",
    "generate:release": "cross-env environment=release nuxt generate",
    "generate:prod": "cross-env environment=production nuxt generate"
}

npm run generate:          默认是正式环境的包
npm run generate:dev        打包开发环境下的静态包
npm run generate:test       打包测试环境下的静态包
npm run generate:pre        打包演示环境下的静态包
npm run generate:release    打包预发布环境下的静态包
npm run generate:prod       打包正式环境下的包

三、在axios.js中进行全局配置请求地址

if (process.env.environment === 'test') {
  baseURL = 测试环境的请求地址'
} else if (process.env.environment === 'presentation') {
  baseURL = '演示环境的请求地址'
} else if (process.env.environment === 'release') {
  baseURL = '预发布环境的请求地址'
} else if (process.env.environment === 'production') {
  baseURL = '正式环境的请求地址'
}

这样配置后,就不用每次打包去更改请求地址了,配置好后直接用对应命令打包即可,美滋滋~~~~~~