打字稿/节点:错误 [ERR_MODULE_NOT_FOUND]:找不到模块

时间:2021-01-03 15:13:52

标签: javascript node.js typescript

我看到了我在标题中指定的错误,这里现有的解决方案似乎都没有帮助,所以我希望有人可以让我了解正在发生的事情。

我在我的项目中使用 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 模块有关,还是其他问题?

提前致谢!

-克里斯

1 个答案:

答案 0 :(得分:3)

向 Node.js 提供 ES6 模块时需要使用 fully-qualified imports

就您而言,这意味着将 .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 和朋友)解决这个问题。现在这些功能正以一流的方式登陆在 Node 中,您会遇到一些额外旧工具为您提供的 Magically™ 功能,但实际上在规范中并非如此!