This blog post describes how to use TypeScript to create npm packages with CommonJS modules. All the artifacts that are shown can be downloaded via the GitHub repository [ts-demo-npm-cjs](https://github.com/rauschma/ts-demo-npm-cjs) (I deliberately have not published it to npm).

Required knowledge: You should be familiar with how npm packages work.

Limitations

We are using what TypeScript currently supports best:

  • All TypeScript code is compiled to CommonJS modules with the filename extension .js.
  • We only import CommonJS modules.

Especially on Node.js, TypeScript currently doesn’t really support ECMAScript modules and filename extensions other than .js.

The repository ts-demo-npm-cjs

This is how the repository ts-demo-npm-cjs is structured:

ts-demo-npm-cjs/
  .gitignore
  .npmignore
  dist/   (created on demand)
  package.json
  ts/
    src/
      index.ts
    test/
      index_test.ts
  tsconfig.json

Apart from the package.jsonfor the package, the repository contains:

  • index.ts: the actual code of the package
  • index_test.ts: a test for index.ts
  • tsconfig.json: configuration data for the TypeScript compiler

package.json contains scripts for compiling:

  • Source: directory ts/ (TypeScript code)
  • Target: directory dist/ (CommonJS modules; the directory doesn’t yet exist in the repository)

This is where the compilation results for the two TypeScript files are put:

ts/src/index.ts       --> dist/src/index.js
ts/test/index_test.ts --> dist/test/index_test.js

#commonjs #npm #typescript

Creating CommonJS-based Npm Packages via TypeScript
2.30 GEEK