我看到我在标题中指定的错误,这里现有的解决方案似乎都没有帮助,所以我希望有人可以让我了解正在发生的事情。
我在我的项目中使用 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
和我的 typescript 文件(此时是否应该这样做,因为它是失败的 Node ??)看起来像这样: {
"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 模块有关,还是有其他问题?预先感谢!
-克里斯
最佳答案
您需要使用 fully-qualified imports将 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”和 detailed more here),以及更现代的 ECMAScript 模块——但在此期间,许多在其中一种和另一种之间转换的工具会为您解决这个问题(即 Webpack 和 friend 们。)现在这些功能在 Node 中以一流的方式登陆,您会遇到一些旧工具 Magically™ 为您做的额外事情,但在规范中实际上并没有以这种方式工作!
关于javascript - typescript /Node : Error [ERR_MODULE_NOT_FOUND]: Cannot find module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65551383/