簡體   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