首页 > 解决方案 > 有什么方法可以在 codegen.yaml 中使用 @next/env 吗?

问题描述

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

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

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 文档中的文档示例

注意:Next.js 将自动扩展 .env* 文件中的变量 ($VAR)。这允许您引用其他机密,如下所示:

# .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: \$.

例如:

# .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

标签: next.jsgraphql-codegen

解决方案


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

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

如果你还想用@next/env,你可以把你的codegen.yml转成codegen.js导入@next/env。比如我原来的 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.

这是Github 上的一个问题,对我有帮助。


推荐阅读