Package Deployment

Change Topic
  • Compile - basics of how to compile and execute a basic program and other common tools
  • Modules - how to create a reusable module in the local project. How to mange exports and imports into a consuming module.
  • Import Package - how add an external package to a program and import it. How to upgrade to new revisions and lock to a specific version.
  • Publish a Package - how to author and publish a package for external consumption
  • Tests - how to add tests to a package that can be run as part of CI/CD
  • Custom Tools - how to incorporate custom tools as part of the build process (e.g. openapi code generation)

TypeScript Package and Deploy

Select Language


Compile

To compile a TypeScript program, install the TypeScript compiler:

npm install -g typescript

Create a simple index.ts file:

const message: string = "Hello, TypeScript!"; console.log(message);

Compile the file:

tsc index.ts

This generates an index.js file that can be executed with Node.js:

node index.js

Modules

Create a module in math.ts:

export function add(a: number, b: number): number { return a + b; }

Consume it in index.ts:

import { add } from "./math"; console.log(add(2, 3));

Compile and run:

tsc && node index.js

Import Package

To add an external package, use npm:

npm install lodash

Import and use it in index.ts:

import _ from "lodash"; console.log(_.capitalize("hello world"));

Lock to a specific version:

npm install lodash@4.17.21

Upgrade a package:

npm update lodash

Publish a Package

  1. Initialize a package:

    npm init -y
  2. Add TypeScript support:

    npm install typescript --save-dev
  3. Write a module in index.ts:

    export function greet(name: string): string { return `Hello, ${name}!`; }
  4. Configure package.json:

    "main": "dist/index.js", "types": "dist/index.d.ts",
  5. Publish:

    npm login npm publish

Tests

Install a test framework:

npm install --save-dev jest @types/jest ts-jest

Configure Jest in jest.config.js:

module.exports = { preset: "ts-jest", testEnvironment: "node", };

Create math.test.ts:

import { add } from "./math"; test("adds 1 + 2 to equal 3", () => { expect(add(1, 2)).toBe(3); });

Run tests:

npm test

Custom Tools

Example: OpenAPI code generation

  1. Install OpenAPI generator:

    npm install @openapitools/openapi-generator-cli -g
  2. Generate TypeScript client:

    openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o generated-client
  3. Use it in a project:

    import { ApiClient } from "./generated-client"; const client = new ApiClient();