一、问题描述
今天遇到一个nuxt(版本:3.0.0-rc.2)项目,在测试环境发布后,发现服务端请求的域名居然是正式环境的配置,根据代码走查,怀疑测试环境编译得到的process.env.NODE_ENV
值错误导致。
项目具体配置如下:
// package.json
...
"scripts": {
...
"build:test": "cross-env NODE_ENV=test nuxt build",
...
},
...
// env.js
const env = {
test: {
'API_URL': 'http://test-domain'
},
production: {
'API_URL': 'http://prod-domain'
},
}
export default env[process.env.NODE_ENV]
// plugins/fetch.js
import envConfig from '../env.js'
const fetch = (url, options) => {
const baseUrl = process.client ? '' : envConfig.API_URL
const fetchOptions = { ... }
return new Promise((resolve, reject) => {
$fetch(url, fetchOptions).then((res) => {
...
}
}
}
二、问题排查
在执行编译命令是输出process.env.NODE_ENV:
// nuxt.config.ts
console.log(process.env.NODE_ENV)
而此时编译得到的.output\public\_nuxt\entry-04fcc700.mjs
中有关env.js
的代码却是production
环境。
目前未排查到具体原因,待后续研究。
三、解决方案
采用runtimeConfig
,官方文档《Environment Variables and Private Tokens》提到:
The runtimeConfig API exposes values like environment variables to the rest of your application. By default, these keys are only available server-side. The keys within runtimeConfig.public are also available client-side.
那么只需要:
// nuxt.config.ts
import envConfig from './env.js'
export default defineNuxtConfig({
runtimeConfig : {
public: {
API_URL: envConfig.API_URL
}
},
...
}
// plugins/fetch.js
const fetch = (url, options) => {
const runtimeConfig = useRuntimeConfig()
const baseUrl = process.client ? '' : runtimeConfig.public.API_URL
const fetchOptions = { ... }
return new Promise((resolve, reject) => {
$fetch(url, fetchOptions).then((res) => {
...
}
}
}