繁体   English   中英

请求的模块“graphql”应为 CommonJS 类型

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

我正在运行我的服务:

"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. 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 文档

多么痛苦

import pkg1 from 'express-graphql';

import pkg from 'graphql';

const { graphqlHTTP } = pkg1;

const { buildSchema } = pkg;

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

import graphql from 'graphql';

const { buildSchema } = graphql; 

在 Windows 和节点 14 上运行针对 ES2022 的 ESM 模块时得到这个。

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

当您的本地机器节点版本比您项目中使用的节点版本太旧时会发生这种情况(检查 packahe.json 文件)。 使用 NVM(节点版本管理器)来使用与项目相同的节点版本或更高的稳定节点版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM