从外部节点模块导入打字稿

2024-04-23

我想将我的应用程序拆分为不同的节点模块,并有一个主模块来构建所有其他模块,并且我想将 typescript 与 es6 模块一起使用。

这是我计划的项目结构:

  • main
    • node_modules
      • dep-a
      • dep-b
  • framework
    • interfaces
      • IComponent.ts
  • dep-a
    • components
      • test.ts
    • node_modules
      • 框架
    • index.ts
  • dep-b
    • node_modules
      • 框架

我希望能够在框架中定义可以在 dep-a、dep-b 和 main 中使用的接口。

我该如何正确设置?我可以编译主模块中的所有内容吗?我是否需要为框架、dep-a、...和另一个打字文件创建不同的包?对此最好的方法是什么?

我已经设置了一些测试文件和文件夹,并使用 npm link 链接依赖项和 webpack 来捆绑文件,但我总是遇到找不到文件的问题:

error TS2307: Cannot find module 'framework/interfaces/IComponent'

and

Module not found: Error: Cannot resolve 'file' or 'directory' ./components/test

TL;DR使用以下命令生成模块的声明declaration: true in tsconfig.json并在中指定生成的类型的文件typings的条目package.json file

框架

Use a tsconfig与此类似的文件:

{
       "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": true,
        "noImplicitAny": true,
        "removeComments": true,
        "outDir": "dist",
        ...
    },
    "files": [
         ...
    ]
}

重要的是declaration: true这将在 dist 目录中生成内部声明

假设有一个index.ts文件(重新)导出所有有趣的部分framework, 创建一个package.json文件带有main and typingsEntry分别指向生成的js和生成的声明,即

{
   "name": "framework",
   "main": "dist/index.js",
   "typings": "dist/index.d.ts",
   ...
 }

将此模块提交到 git 存储库,例如 bitbucket:“https://[电子邮件受保护]/myUser/framework.git https://myUser@bitbucket.org/myUser/framework.git"

dep-a

in package.json创建依赖关系framework

{
    "dependencies": {
        "framework":     "https://[email protected] /cdn-cgi/l/email-protection/myUser/framework.git"
    },
}

这就对了。

import * from 'framework'

将拉取依赖with自动打字

显然,可以这样做dep-a做了什么框架即生成声明、更新 package.json 并使用dep-a作为嵌入类型的模块main

注意:如果您不想通过外部 git 存储库访问,则可以在 package.json/dependencies 中添加文件 URL

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从外部节点模块导入打字稿 的相关文章

随机推荐