繁体   English   中英

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

[英]Typescript/Node: Error [ERR_MODULE_NOT_FOUND]: Cannot find module

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

我在我的项目中使用 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'。 js'

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 文件(此时是否应该这样做,因为它是失败的节点??)看起来像这样:

    {
        "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™ 正在做的其他事情对你来说,但实际上并没有在规范中那样工作!

暂无
暂无

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

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