【问题标题】:The requested module 'graphql' is expected to be of type CommonJS请求的模块“graphql”应为 CommonJS 类型
【发布时间】:2021-01-14 13:11:46
【问题描述】:

我正在运行我的服务:

"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 - 注意它是模块类型

{
    "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 - 将 api.js 作为 ES6 模块导入

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 - 能够导入 express 但在导入 GraphQL 通用 JS 模块时遇到问题

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;

启动脚本出错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.

参考import { buildSchema } from 'graphql';

所以我尝试了这个:

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

但是我在这里收到了 TS 错误...也许我现在需要解决这个问题,但不确定如何解决:

TypeError: buildSchema is not a function

也试过了:

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

错误ReferenceError: require is not defined

所以我不确定如何将这两个项目导入 api.ts

GraphQL docs

【问题讨论】:

    标签: javascript node.js graphql


    【解决方案1】:

    真是头疼

    import pkg1 from 'express-graphql';
    
    import pkg from 'graphql';
    
    const { graphqlHTTP } = pkg1;
    
    const { buildSchema } = pkg;
    

    【讨论】:

    • 知道为什么会这样吗?文档表明不需要它。 (我遇到了同样的问题)。
    【解决方案2】:

    按照以下步骤操作,如果仍然不起作用,请更新您的节点版本。

    import graphql from 'graphql';
    
    const { buildSchema } = graphql; 
    

    【讨论】:

      【解决方案3】:

      在 Windows 和 Node 14 上运行针对 ES2022 的 ESM 模块时遇到此问题。

      更新到节点 16 解决了这个问题。

      【讨论】:

        猜你喜欢
        • 2020-11-16
        • 2021-11-11
        • 1970-01-01
        • 2018-07-13
        • 2017-06-21
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多