[英]relay-compiler unable to extract and use graphql queries in Typescript
我尝试将中继与Typescript react starter一起使用,但遇到了多个问题。
似乎 babel-plugin-relay 无法感知中继编译器提取的 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和#2293的工作,我找到了解决方案。
以下是步骤:
修改 webpack 配置以包含一个 babel 加载器(typescript starter 只有一个 ts-loader)。
...
test: /\.(ts|tsx)$/,
include: paths.appSrc,
exclude: /node_modules/,
use: [
{ loader: 'babel-loader' },
{
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
},
},
],
...
将 tsconfig 中的target
和module
配置更改为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模块的import
export
语句。
以及编译 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__" }],
],
My.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
这会将您链接到 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.