The requested module 'graphql' is expected to be of type CommonJS

Viewed 1345

I'm running my service with:

"start": "NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --es-module-specifier-resolution=node --no-warnings dist/server-new/server.js"

package.json - notice it's type module

{
    "name": "some-name",
    "license": "UNLICENSED",
    "version": "0.0.0",
    "description": "",
    "type": "module",
    "engines": {
        "node": "14.x",
        "npm": "6.14.x"
    },
...
}

tsconfig.json

{
    "extends": "../../tsconfig",
    "compilerOptions": {
        "noEmit": false,
        "rootDir": "."           /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
        "outDir": "../../dist"  /* Redirect output structure to the directory. */
    },
    "module": "ESNext",
    "include": ["./*.ts", "package.json"],
    "resolveJsonModule": true
}

server.ts - imports api.js as an ES6 module

import cluster from 'cluster';
import os from 'os';
import App from './api.js';

...
    App.listen(port, () => {
        console.log(`express is listening on port ${port}`);
    });

api.ts - is able to import express but having problem importing GraphQL common JS modules

import compression from 'compression';
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { buildSchema } from 'graphql';
import CompanyController from './Controllers/CompanyController';


const App = express()
    .use(compression())
    ....
    );
export default App;

Error during the start script: SyntaxError: The requested module 'graphql' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.

referring to import { buildSchema } from 'graphql';

So I tried this:

import * as graphQL from 'graphql';
const { buildSchema } = graphQL;

but then I get the TS error here...maybe I need to resolve this now but not sure how:

TypeError: buildSchema is not a function

Also Tried:

// eslint-disable-next-line @typescript-eslint/no-var-requires
const { buildSchema } = require('graphql');

Error: ReferenceError: require is not defined

So I'm not sure how in the world I'll import these two items here into api.ts.

GraphQL docs

3 Answers

what a pain in the ass

import pkg1 from 'express-graphql';

import pkg from 'graphql';

const { graphqlHTTP } = pkg1;

const { buildSchema } = pkg;

Follow steps below and if it still doesn't work update your node version.

import graphql from 'graphql';

const { buildSchema } = graphql; 

Got this while running ESM modules targeting ES2022 on Windows and Node 14.

Updating to Node 16 fixed the issue.

Related