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.
We are using what TypeScript currently supports best:
.js
.Especially on Node.js, TypeScript currently doesn’t really support ECMAScript modules and filename extensions other than .js
.
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.json
for the package, the repository contains:
index.ts
: the actual code of the packageindex_test.ts
: a test for index.ts
tsconfig.json
: configuration data for the TypeScript compilerpackage.json
contains scripts for compiling:
ts/
(TypeScript code)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