错误:无法使用来自另一个模块或领域的 GraphQLSchema“[object GraphQLSchema]”

Mat*_*zer 12 javascript node.js ecmascript-6 graphql graphql-js

鉴于以下代码:

import { graphql } from 'graphql'
import graphqlTools from 'graphql-tools'

const { makeExecutableSchema } = graphqlTools

const typeDefs = `
type Query {
   as: [A]
}

type A {
   x: Int,
   y: Int
}
`
const schema = makeExecutableSchema ({ typeDefs })

graphql(schema, '{ as { x, y } }').then(console.log)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

错误:无法使用来自另一个模块或领域的 GraphQLSchema“[object GraphQLSchema]”。

确保 node_modules 目录中只有一个“graphql”实例。如果不同版本的“graphql”是其他依赖模块的依赖,使用“resolutions”保证只安装一个版本。

这是怎么回事?

Ego*_*gor 11

graphql您安装的模块版本与 安装和使用的版本不同时,也可能出现这种情况graphql-tools

我发现您可以通过以下任一方式纠正此问题:

  1. 更改graphql项目package.json文件中的版本以完全匹配graphql-toolspackage.json文件中依赖的内容。

  2. 删除graphql作为依赖项并安装graphql-tools. 然后您将自动接收安装的任何graphql模块版本graphql-tools(只要您不依赖于安装另一个冲突版本的任何其他软件包)。

在其他情况下,您可能拥有正确的版本,但可能会安装多次。您可以使用npm ls graphql来查看所有已安装的版本。尝试运行npm dedupe以删除重复的安装。


Mat*_*zer 8

发生这种情况是因为graphql-tools模块从其 CommonJS 模块导入graphql,而我的代码从 ES 模块导入。也就是说,我自己的模块中的每个对象都来自ES模块,而graph-tool's则不是。

解决方案

这就像从graphqlCommonJS 模块中导入任何内容一样简单,并且来自graphql和的两个对象都graphql-tools能够相互通信:

import graphql_ from 'graphql/index.js'
import graphqlTools from 'graphql-tools'

const { graphql } = graphql_
const { makeExecutableSchema } = graphqlTools

const typeDefs = `
type Query {
   as: [A]
}

type A {
   x: Int,
   y: Int
}
`
const schema = makeExecutableSchema ({ typeDefs })

graphql(schema, '{ as { x, y } }').then(console.log)
Run Code Online (Sandbox Code Playgroud)


小智 6

我的问题是由于 webpack 配置错误,两个 graphql 文件都得到了解决.js.mjs

根本原因:

TypeMapper.mjs文件中graphql-compose,导入语句没有文件扩展名,这在 webpack 包上是失败的。为了解决这个问题,我需要添加fullySpecified:false到 webpack 配置中。

{
  test: /\.m?js/,
  include: /node_modules/,
  type: "javascript/auto",
  resolve: {
    fullySpecified: false
  }
}
Run Code Online (Sandbox Code Playgroud)

我还修改了解析语句,例如

resolve: {
  extensions: [".ts", ".js", ".mjs"] // that was the actual problem
}
Run Code Online (Sandbox Code Playgroud)

由于fullySpecifiedconfig 已设置为false,webpack 尝试解析文件而不考虑resolve.extentions配置顺序的扩展名。由于该配置中的顺序错误,尽管所有其他文件都使用一个,但graphql带有.jsext 的文件已被解析.mjs

解决方案:

只需将配置重新resolve.extensions排序为

resolve: {
  extensions: [".ts", ".mjs", ".js"]
}
Run Code Online (Sandbox Code Playgroud)