打字稿/节点:错误[ERR_MODULE_NOT_FOUND]:找不到模块
我看到了我在标题中指定的错误,这里现有的解决方案似乎都没有帮助,所以我希望有人能让我了解正在发生的事情。
我在我的项目中使用 Typescript 和 Node。TS 编译一切都很好......我最终得到了以下预期:
projectHome/
dist/
schema/
schema.js
index.js
当我node ./dist/index.js从项目主页运行时,出现错误无法找到从“/home/me/projectHome/dist/index.js”导入的模块“/home/me/projectHome/dist/schema/schema”
index.js 中的相对导入如下:
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import typeDefs from './schema/schema';
我的 schema.ts 文件包含:
import { ApolloServer, gql } from 'apollo-server-express'
import { GraphQLScalarType } from 'graphql'
const typeDefs = gql`
...(edited for brevity/sanity)
`
export default typeDefs
和我的打字稿文件(在这一点上应该很重要,因为它是失败的节点??)看起来像这样:
{
"compilerOptions": {
"target": "ES6",
"module": "ES6",
"lib": ["ES6"],
"allowJs": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"files": ["src/@types/graphql.d.ts"],
"include": ["src/**/*", "serverInfo.json"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
请注意,我不能使用 commonjs,因为当我使用时,一些与异议相关的代码会失败。问题实际上与使用 ES6 模块有关,还是其他问题?
预先感谢!
-克里斯
回答
将 ES6 模块提供给 Node.js 时,您需要使用完全限定的导入。
在您的情况下,这意味着将.js扩展添加到您的schema导入中:
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
-import typeDefs from './schema/schema';
+import typeDefs from './schema/schema.js';
您的困惑可能来自这样一个事实,即这种需求在传统的require()样式引用(称为“CommonJS”,这里有更多详细信息)和更现代的 ECMAScript 模块之间发生了变化——但在此期间,许多工具在一个和另一个会为你处理这个问题(即Webpack和朋友)。现在这些功能以一流的方式登陆 Node,你会遇到一些旧工具 Magically™ 为你做的其他事情,但实际上在规范中不是这样工作的!
THE END
二维码