【问题标题】:Built library cannot be imported in other project构建的库不能导入其他项目
【发布时间】:2020-01-20 10:12:33
【问题描述】:

我需要构建一个库,它是一个soap API 的包装器。库的结构如下:

|-node_modules
|
|-src
|  |-soapWrapperLibrary.ts
|  |-soapLibraryClient.ts
|
|-types
|  |-soapResponseType.d.ts

library 使用client,它返回我定义的对象soapResponseType

这个库将用于另一个实习项目。无需将任何内容推送到 npm 或类似内容。我尝试使用tsc 编译它,但编译结果忽略了我定义的类型(soapResponseType.d.ts)。这导致在导入我的库时出错,因为找不到定义文件。

我尝试了几种与 typeRoots 编译类型相关的方法,但没有结果。

我希望tsc 将我的所有文件编译为一个包或可以作为一个整体导入的东西,其中包含类型和类。

使用以下选项,我唯一得到的是下一个结构,没有任何 soapResponseType.d.ts 的痕迹:

|-dist
|  |-lib
|  |  |-soapWrapperLibrary.js
|  |  |-soapWrapperLibrary.js.map
|  |  |soapLibraryClient.js
|  |  |soapLibraryClient.js.map
|  |-types
|  |  |-soapWrapperLibrary.d.ts
|  |  |soapLibraryClient.d.ts

命令tsc --listFiles 显示了我创建的三个文件:两个.ts 文件和一个.d.ts

用于复制的回购https://github.com/TheoSl93/buildLibraryTest

这些是我的tsconfig.jsonpackage.json

tsconfig

{
  "compilerOptions": {
    "target": "es5",
    "module":"es2015",
    "strict": true,
    "declaration": true,
    "outDir": "dist/lib",
    "declarationDir": "dist/types",
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "removeComments": true,
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./types"
      ]
    },
    "lib": ["es2015", "es2016", "es2017", "dom"],
    "emitDecoratorMetadata": true,
    "typeRoots": [
      "node_modules/@types",
      "types/*"
    ]
  },
  "typedocOptions": {
    "mode": "modules",
    "out": "docs",
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "test/**/*.ts",
    "test/**/*.tsx"
  ],
  "exclude": [
    "node_modules",
    "test"
  ],
}


  "name": "soap-library",
  "version": "0.0.1",
  "description": "reproduce for stackoverflow",
  "main": "dist/lib/soapLibraryClient.js",
  "repository": "https://github.com/TheoSl93/buildLibraryTest.git",
  "author": "Theo Sloot",
  "license": "MIT",
  "scripts": {
    "prebuild": "rm -rf dist",
    "build": "tsc --module commonjs"
  },
  "sideEffects": false,

此时:

  • 有没有什么方法可以在编译时只使用tsc包含自制定义?
  • 真的有必要吗?可以只使用.ts 文件而不是编译的.js 文件来导入这个库吗?

【问题讨论】:

  • 我想这会回答你的问题:stackoverflow.com/questions/59681908/…
  • @PedroMutter 不是真的,但谢谢!我的类的 .d.ts 文件在 dist/types 中按预期生成,我缺少的是我已经在我的 src soapResponseType.d.ts 中所做的定义。我需要在我的dist 文件夹中的那个文件

标签: javascript typescript typescript2.0 tsc type-declaration


【解决方案1】:

要让 typescript 使用您的类型定义文件 (soapResponseType.d.ts),您需要在您的 types 文件夹中将 soapResponseType.d.ts 定义为 soapResponseType.ts,它将生成 soapResponseType.d.tssoapResponseType.ts 的确切内容,因为两者都是.ts 文件,不需要转译。此外,您应该考虑将 types 文件夹移动到 src 文件夹中,因为您的 tsconfig 配置为仅编译 src 文件夹。

【讨论】:

    猜你喜欢
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多