How code is packaged, deployed and reused across different projects, libraries and applications.
Package Deployment
TypeScript Package and Deploy
Compile
Basics of how to compile and execute a basic program and other common tools.
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
Error Loading
Missing
Modules
Create a reusable module in the local project. Manage exports and imports into a consuming module.
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
Missing
Import Package
Add an external package to a program and import it. Upgrade to new revisions and lock to a specific version.
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
Missing
Publish a Package
Author and publish a package for external consumption.
-
Initialize a package:
npm init -y
-
Add TypeScript support:
npm install typescript --save-dev
-
Write a module in
index.ts
:export function greet(name: string): string { return `Hello, ${name}!`; }
-
Configure
package.json
:"main": "dist/index.js", "types": "dist/index.d.ts",
-
Publish:
npm login npm publish
Missing
Tests
Add tests to a package that can be run as part of CI/CD.
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
Missing
Custom Tools
Incorporate custom tools as part of the build process (e.g., OpenAPI code generation).
Example: OpenAPI code generation
-
Install OpenAPI generator:
npm install @openapitools/openapi-generator-cli -g
-
Generate TypeScript client:
openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o generated-client
-
Use it in a project:
import { ApiClient } from "./generated-client"; const client = new ApiClient();