我想发布一个包,其中包含*.graphql“模块”的类型声明,并让项目使用该包,以便它们可以为在其他文件中编写的查询编写import语句。这个是可能的吗?
这是我到目前为止所掌握的。
我在一个名为graphql.d.ts的文件中有以下类型。
declare module '*.graphql' {
import { DocumentNode } from 'graphql';
const Schema: DocumentNode;
export default defaultDocument;
}我的package.json是这样的。
{
"name": "@my-private-scope/type-graphql-imports",
"version": "1.0.0",
"types": "graphql.d.ts",
"files": [
"graphql.d.ts"
],
"peerDependencies": {
"graphql": ">=14.0.0"
}
}但在发布此包并将其导入到另一个项目后,我遇到了以下错误。
error TS2307: Cannot find module './query.graphql' or its corresponding type declarations.
有没有办法对项目进行配置,使这些类型对编译器可见?
发布于 2021-11-22 16:39:03
如果我理解正确的话,这里有两个问题/答案,即你遗漏了两件事
有关如何生成/模块化graphql queries
fix the for the typescript compiler errors your your。让我们开始,请考虑答案和他们的子选项。
答案A:
重用/模块化--要为GraphQl查询生成/创建类型脚本模块/组件,可以使用3个选项,即
通过使用
,然后使用片段,您可以像这样组件化它们,从而更简单地使用GraphQl Generator,使用GraphQl Fragments Ref.来滚动您自己的配置
选项1:有一个内置的生成器,你可以用它来简化与webpack的组合。
中列出的代码
generates: src/api/user-service/queries.d.ts
documents: src/api/user-service/queries.graphql
plugins:
- typescript-graphql-files-modules
config:
# resulting module definition path glob: "*\/api/user-service/queries.graphql"
modulePathPrefix: "/api/user-service/"my-query.graphql文件中有一个名为MyQuery的查询,此模板将生成以下代码:declare module '*/my-query.graphql' {
import { DocumentNode } from 'graphql';
const MyQuery: DocumentNode;
export { MyQuery };
export default defaultDocument;
}
Accordingly, you can import the generated types and use it in your code:
import myQuery from './my-query.graphql';
// OR
import { myQuery } from './my-query.graphql';选项2更简单,例如
简单的表单,我推荐使用webpack loader来供给您的webpack config apollo
loaders: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader'
}
]避免在queries.graphql中使用双引号和特殊字符
query GetAllRoles($value: String) {
Role(filter: { role: $value }) {
role
}
}现在,您可以将其与查询值一起重用
import GetAllRoles from './queries.graphql'
.....
this.apollo.query({
query: GetAllRoles,
variables: {
value: GetAllRoles,
}
})
.subscribe(....)有关模块创建和resolvers here的更多示例和细节,可帮助您
答案B:
修复您所面临的的Typescript compiler errors
首先,graphql的typescript definitions/types是missing,您必须手动配置/添加/扩展Typescript definition。
// in your webpack.d.ts
declare module "*.gql" {
const content: any;
export default content;
}
declare module "*.graphql" {
const content: any;
export default content;
}其次,如果这不能修复它,那么也请尝试在tsconfig.json中添加这个,以防止typescript编译器将模块类型应用于导入的javascript。
// in your tsconfig.json
{
"compilerOptions": {
...
"allowJs": true,
"checkJs": false,
...
}
}https://stackoverflow.com/questions/69915200
复制相似问题