nuxt.config.js
modules: [
'@nuxtjs/dotenv'
],
服务器/ index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '0.0.0.0'
const port = 8080
app.set('port', port)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
const Storage = require('@google-cloud/storage')
const dotenv = require('dotenv')
async function getEnv() {
if (config.dev) {
dotenv.config({ path: '.env' })
console.log('Environment local .env file loaded.')
console.log(process.env.LOCALE)
return
}
try {
const bucketName = 'env-var'
const dotEnvSourcePath = `.env`
const dotEnvDestinationPath = `/tmp/${dotEnvSourcePath}`
const storage = new Storage({})
await storage
.bucket(bucketName)
.file(dotEnvSourcePath)
.download({ destination: dotEnvDestinationPath })
console.log(
`gs://${bucketName}/${dotEnvSourcePath} downloaded to ${dotEnvDestinationPath}.`
)
dotenv.config({ path: dotEnvDestinationPath })
} catch (err) {
console.error('ERROR:', err)
}
}
async function afterEnvProcess() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
const fs = require('fs')
const dotEnvExists = fs.existsSync('.env')
}
getEnv()
.then(r => afterEnvProcess())
.catch(e => console.log(e))
我得到的值process.env.<variable>
作为undefined
运行生产应用程序时。在开发中运行时,我可以正确获取值。看来env变量没有传递给nuxt env属性。
编辑1:当我使用process.env控制台记录环境变量时,我可以在Google云日志中看到正确的值。但同时这些控制台日志语句在浏览器控制台中显示未定义
在构建时捆绑了Env变量。因此,在为生产而构建时需要设置它们
它们将在运行时在server / index.js中可用,但是在nuxt build dist时,将process.env。*替换为在构建时传递的值,因此启动服务器时传递的内容并不重要变量。