gpt4 book ai didi

next.js - 有什么办法可以在 codegen.yaml 中使用 @next/env 吗?

转载 作者:行者123 更新时间:2023-12-05 03:37:03 25 4
gpt4 key购买 nike

我想知道当我运行 yarn codegen 时,是否有办法使用 @next/env 替换 codegen.yaml 中的变量:

graphql-codegen -r dotenv/config --config codegen.yml - 这是加载 dot env 的代码生成示例

graphql-codegen -r @next/env --config codegen.yml - 这就是我想要实现的

当我调用它时,我得到

${SERVER_API_URL}/graphql 变为 undefined/graphql

我的用例是:

# .env
HOST=https
API_DOMAIN=example.com
SERVER_API_URL=$HOST://$API_DOMAIN
# codegen.yaml
schema: ${SERVER_API_URL}/graphql

为什么要使用 @next/env? 它替换了 .env 中的变量,我附上来自 next.js 文档的文档示例:

Note: Next.js will automatically expand variables ($VAR) inside ofyour .env* files. This allows you to reference other secrets, like so:

# .env
HOSTNAME=localhost
PORT=8080
HOST=http://$HOSTNAME:$PORT

If you are trying to use a variable with a $ in the actual value, it needs to be escaped like so: \$.

For example:

# .env
A=abc

# becomes "preabc"
WRONG=pre$A

# becomes "pre$A"
CORRECT=pre\$A

来源:https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables

最佳答案

您不能通过-r 标志直接使用@next/env。但是你仍然有几个选择。例如,您可以直接寻址所需的 .env 文件:

DOTENV_CONFIG_PATH=./.env.local graphql-codegen --config codegen.yml -r dotenv/config

如果你仍然想使用@next/env,你可以将你的codegen.yml转换成codegen.js并导入@next/环境。比如我原来的YML:

overwrite: true
schema:
- https://graphql.fauna.com/graphql:
headers:
Authorization: 'Bearer ${FAUNA_ADMIN_KEY}'
documents: null
generates:
src/generated/graphql.ts:
plugins:
- typescript
- typescript-operations
- typescript-graphql-request
./graphql.schema.json:
plugins:
- 'introspection'

我重写成JS:

const { loadEnvConfig } = require('@next/env')
loadEnvConfig(process.cwd())

module.exports = {
overwrite: true,
schema: {
'https://graphql.fauna.com/graphql': {
headers: {
Authorization: `Bearer ${process.env.FAUNA_ADMIN_KEY}`,
},
},
},
documents: null,
generates: {
'src/generated/graphql.ts': {
plugins: [
'typescript',
'typescript-operations',
'typescript-graphql-request',
],
},
'./graphql.schema.json': { plugins: ['introspection'] },
},
}

然后使用 graphql-codegen --config codegen.js 生成代码。

这是一个 issue on Github这对我有帮助。

关于next.js - 有什么办法可以在 codegen.yaml 中使用 @next/env 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69461989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com