What is the story for creating and consuming TypeScript libraries?

前端 未结 2 1445
Happy的楠姐
Happy的楠姐 2021-02-06 05:15

I\'ve been using TypeScript here and there for web applications and have referenced public type definitions made available through Definitely Typed but one thing that has always

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 05:32

    To create a TS library that will be consumed by a TS project you don't have to do a whole lot.

    (Sorry if the example is overly verbose.)

    The library

    Assuming your source files are writting in TypeScript, you need the following config tweaks:

    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
    }
    

    The important thing here is basically declarations: true, which tell the TS compiler to generate the d.ts files.

    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",
        ...
      }
    }
    

    The important things here is "main" and "typings" which is the entry point for the service in the library. So if someone were to require("my-typescript-library") then the file listed here would be used. The typings field is similar but obviously helps TypeScript.

    You then push this library to Github, or Bitbucket, or where ever.

    The consumer

    You don't need much here.

    package.json

    Add a dependency to your library:

    {
      ...,
      "dependencies": {
        "my-typescript-library": "git+ssh://bitbucket.org/you/my-typescript-library",
        ...
      }
    }
    

    You will need an SSH key in this example.

    Then you just import the lib.

    my_file.ts

    import {MyService} from "my-typescript-library";
    

    So there you have it, a TypeScript lib being used in a TypeScript app. Hope that is enough of an answer (and clear enough), otherwise just drop me a line.

提交回复
热议问题