graphql-js: "one instance of graphql" error when using esm package.

When using esm package (https://github.com/standard-things/esm) even most simple package.json configurations (only dependancies are esm and graphql-yoga) results in the Error: Cannot use GraphQLSchema "[object Object]" from another module or realm. error when using imports.

node -r esm testWithImport.js will fail while node testWithRequire.js and node -r esm testWithRequire.js will work.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 16 (5 by maintainers)

Most upvoted comments

This happens if you were to add a new npm script called

"mjsImport": "node --experimental-modules serverWithImport.mjs"

and a test file serverWithImport.mjs:

import graphglYoga from 'graphql-yoga';
import { GraphQLObjectType, GraphQLSchema, GraphQLString } from "graphql";

const { GraphQLServer } = graphglYoga

var Something = new GraphQLObjectType({
    fields: {
        else: { type: GraphQLString },
    },
    name: 'Something',
})

var schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        fields: {
            something: {
                type: Something,
            },
        },
        name: 'Query',
    }),
});

var server = new GraphQLServer({ schema });
const instance = server.start(); // defaults to port 4000

too.

The issue is that graphql-yoga is CJS (and loads the CJS entry of graphql) but you’re loading the ESM version of graphql.

Because graphgl is running two entry points they create 2 separate instances (a limitation of their current dual approach). The way around it is for graphql to instantiate their instances in CJS and export them for the ESM entry to consume.