中继编译器无法在 Typescript 中提取和使用 graphql 查询

relay-compiler unable to extract and use graphql queries in Typescript

我尝试将中继与 Typescript react starter 一起使用,但 运行 遇到了多个问题。

似乎 babel-plugin-relay 无法感知 relay-compiler 提取的 graphql 语句。这是我的编译器脚本

"relay": "relay-compiler --src ./src --schema ./src/schema.graphql --extensions=tsx --watchman false".

.babelrc

{
   "babel": {
   "presets": [
      "react-app"
   ],
   "plugins": [
     "relay"
   ]
}

这是我的错误,表明 babel 转译存在问题

graphql: Unexpected invocation at runtime. Either the Babel transform was not set up, or it failed to identify this call site. Make sure it is being used verbatim as `graphql`.

基本上问题解决了在转换期间从打字稿中提取 GraphQL 标签。多亏了这些 PR #1710 and #2293.

,我找到了解决方案

步骤如下:

修改 webpack 配置以包含一个 babel 加载器(打字稿启动器只有一个 ts-loader)。

    ...
    test: /\.(ts|tsx)$/,
    include: paths.appSrc,
    exclude: /node_modules/,
    use: [
       { loader: 'babel-loader' },
       {
         loader: require.resolve('ts-loader'),
         options: {
            transpileOnly: true,
         },
       },
    ],
    ...

将tsconfig中的targetmodule配置改为es2015

...
"target": "es2015",
"module": "es2015",
...

添加relay-compiler-language-typescript

yarn add relay-compiler-language-typescript -D

同时添加 babel-plugin-transform-es2015-modules-commonjs

yarn add babel-plugin-transform-es2015-modules-commonjs -D

由于现在我们的目标是 es2015,因此需要此插件来支持 ES 模块 importexport 语句。

以及编译 graphql 语句的脚本

"relay": "relay-compiler --src ./src --schema src/schema.graphql --language typescript --artifactDirectory ./src/__generated__ --watch"

将中继插件指向.babelrc

中使用上述命令生成的工件
"plugins": [
    "transform-es2015-modules-commonjs",
    ["relay", { "artifactDirectory": "./src/__generated__" }],
 ],

我的 .babelrc 看起来像这样

{
    "plugins": [
        [
            // Please note that the "relay" plugin should run before other plugins or presets to ensure the graphql template literals are correctly transformed. See Babel's documentation on this topic.
            "relay",
            {
                "artifactDirectory": "./src/__generated__"
            }
        ],
        [
            "transform-es2015-modules-commonjs",
            {
                "allowTopLevelThis": true
            }
        ]
    ]
}

按照此处的配置步骤进行操作https://github.com/relay-tools/relay-compiler-language-typescript#typescript

这将 link 你到 babel 文档 https://babeljs.io/docs/en/babel-plugin-transform-es2015-modules-commonjs/

这似乎有效。我的 npm 脚本是

"relay": "relay-compiler --src ./src --schema ./data/schema.graphql --language typescript --artifactDirectory ./src/__generated__"

和tsconfig.json包含这个

    "target": "es2015",
    "module": "es2015",

更新

我必须按照此处所述安装 babel-plugin-relay https://create-react-app.dev/docs/adding-relay/

并破解打字稿类型 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/35707