创建和使用TypeScript库的故事是什么?

jpi*_*son 8 libraries typescript

我一直在这里和那里使用TypeScript用于Web应用程序,并引用了通过Definitely Typed提供的公共类型定义但是我总是想到的一件事是如何在TypeScript中创建可重用库,目的是被一个人使用TypeScript应用程序或其他库.

关于该主题的大多数指导似乎直接指向如何为最初在JavaScript中编写的库创建或查找类型定义,但是如何使用TypeScript编写的库,似乎共享生成的js文件和相应的类型定义文件的某种机制应该是一个常见的地方,但我没有找到任何提到任何人试图为私人或公共图书馆这样做.也许我在寻找错误的地方?是否有创建和使用TypeScript库的故事.

Dar*_*ron 5

要创建将由TS项目使用的TS库,您无需做很多事情。

(很抱歉,示例过于冗长。)

图书馆

假设您的源文件是用TypeScript编写的,则需要进行以下配置调整:

tsconfig.json

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "commonjs",
    "removeComments": false,
    "sourceMap": true,
    "outDir": "dist/",
    "declaration": true
  },
  "filesGlob": [
    "**/*.ts",
    "!node_modules/**/*"
  ],
  "exclude": [
    "node_modules",
    "typings/global",
    "typings/global.d.ts"
  ],
  "compileOnSave": true
}
Run Code Online (Sandbox Code Playgroud)

此处重要的一点基本上是declarations: true,它告诉TS编译器生成d.ts文件。

package.json

{
  "name": "my-typescript-library",
  "description": "...",
  "version": "1.0.0",
  "main": "./dist/my.service.js",
  "typings": "./dist/my.service.d.ts",
  "license": "ISC",
  "dependencies": {
    ...
  },
  "devDependencies": {
    "typescript": "^1.8.10",
    "typings":"^1.0.4",
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

这里重要的是“ main”和“ typings”,这是库中服务的入口点。因此,如果有人这样做,require("my-typescript-library")则将使用此处列出的文件。类型字段类似,但显然有助于TypeScript。

然后,您可以将此库推送到Github,Bitbucket或任何地方。

消费者

您在这里不需要太多。

package.json

向您的库添加依赖项:

{
  ...,
  "dependencies": {
    "my-typescript-library": "git+ssh://bitbucket.org/you/my-typescript-library",
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,您将需要SSH密钥。

然后,您只需导入库。

my_file.ts

import {MyService} from "my-typescript-library";
Run Code Online (Sandbox Code Playgroud)

这样就可以在TypeScript应用程序中使用TypeScript库。希望这是一个足够的答案(并且足够清晰),否则请给我留言。


Jul*_*eda -1

好吧,我认为你可以使用模块来达到这个目的,模块就像 C# 中的命名空间,例如

//File Utils.ts
module Utils
{
    export class UtilsClass
    {
        do(param: string)
        {
            //do something
        }
    }
}

//Another ts file
var formatter = new Utils.UtilsClass();
formatter.do("str");
Run Code Online (Sandbox Code Playgroud)

问候,