在 typescript node+express 项目中使用模块中的 typescript 文件的正确方法?当前抛出错误:找不到模块

Posted

技术标签:

【中文标题】在 typescript node+express 项目中使用模块中的 typescript 文件的正确方法?当前抛出错误:找不到模块【英文标题】:Correct way of using typescript files from modules in typescript node+express project? currently throwing Error: Cannot find module 【发布时间】:2019-11-08 14:54:24 【问题描述】:

我有一个打字稿模块@tlabs/models,我只是在 index.ts 中导出:

export * from '../models......'

在每个文件中我有类似的东西:

export const Project = typedModel('projects', ProjectSchema);

我唯一的依赖是 ts-mongoose 在每个文件中导入,就像:

import  createSchema, Type, typedModel, ExtractProps  from 'ts-mongoose';

ts-mongoose 是一个依赖项,它本身需要 mongoose + mongoose 类型。

在我的 typescript 节点项目中,ts-mongoosemongoose 和 @tlabs/models 作为依赖项,@types/mongoose 作为开发依赖项。

运行 tsc 没问题,文件被编译,没有错误被抛出,但尝试运行实际文件却抛出:

Error: Cannot find module '@tlabs/models'

我已经多次重新安装了所有模块,并通过 vscode 检查了 package.json 以及磁盘上的实际文件,它们就在那里。

我错过了什么?

我的 tsconfig 是:


  "include": ["src/**/*"],
  "exclude": ["node_modules", "./node_modules", "./node_modules/*"],
  "compilerOptions": 
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "allowJs": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "noImplicitAny": false,
    "alwaysStrict": true,
    "strictNullChecks": true,
    "types": [],
    "lib": [],
    "experimentalDecorators": true
  


在我的节点项目中使用/导入它的正确方法是什么?

【问题讨论】:

默认情况下,typescript 包含 node_modules/@types @types 下的所有类型,文档还提到 Specify "types": [] 以禁用自动包含 @types 包。 基于在module resolution 上,您是否尝试过从您的 tsconfig 中删除“types:[]”并让编译器执行它的默认模块解析? 最后我从最初的问题中转移了很多方法,我想我只需要从头开始做一个使用直接依赖的 npm 包,因为目前我的文件没有真正发生什么时候我尝试导入它们,这一切都是一团糟...... 这可能是个好主意。如果你仍然有同样的问题,如果你分享你的 package.json 文件也可能会有所帮助。 【参考方案1】:

我的最终 TS 配置:


    "compilerOptions": 
        "target": "es5",
        "module": "commonjs",
        "declaration": true,
        "declarationMap": true,
        "sourceMap": true,
        "outDir": "lib",
        "strict": true,
        "esModuleInterop": true
    ,
    "include": ["src"]


以及相关的package.json配置:


    "main": "lib/index.js",
    "types": "lib",
    "scripts": 
        "tsc": "tsc",
        "build": "tsc -p ."
    ,
    "files": [
        "lib"
    ],

【讨论】:

以上是关于在 typescript node+express 项目中使用模块中的 typescript 文件的正确方法?当前抛出错误:找不到模块的主要内容,如果未能解决你的问题,请参考以下文章

typescript node.js express 路由分隔文件的最佳实践

在 typescript node+express 项目中使用模块中的 typescript 文件的正确方法?当前抛出错误:找不到模块

如何在同一个项目中将 Typescript 与 Angular CLI 和 Express/Node 一起使用?

使用 ts-node 进行测试时,TypeScript Express Api 类不是构造函数

如何将 NewRelic 集成到与 Webpack 捆绑的 Node Typescript Express 服务器中?

Node.js + TypeScript:类型脚本编译代码的语法不明确