Writing a Node.js module in TypeScript
Tags: typescript, javascript, modules, npm
Published: 2017-07-18 11:46:00

---
cover_image: https://thepracticaldev.s3.amazonaws.com/i/f95yffdudrxwziwxon5z.png
title: Writing a Node.js module in TypeScript
published: true
description: Learn how to write a module using TypeScript that can be consumed with both JavaScript and TypeScript in Node.js or the browser.
tags: typescript, javascript, modules, npm
canonical_url: https://www.twilio.com/blog/2017/06/writing-a-node-module-in-typescript.html
---

One of the best things about [Node.js](https://nodejs.org/en/) is its massive module ecosystem. With bundlers like [webpack](https://webpack.github.io/) we can leverage these even in the browser outside of Node.js. Let’s look at how we can build a module with [TypeScript](http://www.typescriptlang.org/) usable by both JavaScript developers and TypeScript developers.

Before we get started make sure that you have Node.js installed – you should ideally have a version of 6.11 or higher. Additionally make sure that you have [npm](https://www.npmjs.com/) or a similar package manager installed.

Let’s build a module that exposes a function that filters out all emojis in a string and returns the list of emoji shortcodes. Because who doesn’t love emojis?

![decorative gif of different emojis](https://www.twilio.com/blog/wp-content/uploads/2017/06/BYDvhRSNstCFMpuIrrcHM4PDwL3e_e_T5PaSf7uQ5FXQ7zMvPaLpqjb1d1jqeb7V7VpC5YzWeminPCESFecPqcvg-wm8noTsZwgI9L0mHnC0Syh7DYCFfVCfVETGZW-yurG6vhDY.png)

##âœ¨ Installing dependencies

First create a new directory for your module and initialize the `package.json` by running in your command line:

```bash
mkdir emoji-search
cd emoji-search
npm init -y
```

The resulting `package.json` looks like this:

```js
{
  "name": "emoji-search",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
```

Now let’s  install some dependencies. First install the TypeScript compiler as a `devDependency` by running:

```bash
npm install typescript --save-dev
```

Next install the `emojione` module.  We’ll use this to convert emojis to their shortcodes like ðŸµ to `:monkey_face:`. Because we will be using the module in TypeScript and the module doesn’t expose the types directly we also need to install the types for `emojione`:

```bash
npm install emojione @types/emojione --save
```

With the project dependencies installed we can move on to configuring our TypeScript project.

## ðŸ”§ Configuring the TypeScript project

Start by creating a `tsconfig.json` file which we’ll use to define our TypeScript compiler options. You can create this file manually and place the following lines into it:

```json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "strict": true
  }
}
```

Alternatively you can auto-generate the `tsconfig.json` file with all available options by running:

```bash
./node_modules/.bin/tsc --init
```

If you decided for this approach just make sure to adjust the `declaration` and `outDir` options according to the JSON above.

Setting the `declaration` attribute to `true` ensures that the compiler generates the respective TypeScript definitions files aside of compiling the TypeScript files to JavaScript files. The `outDir` parameter defines the output directory as the `dist` folder.

Next modify the `package.json` to have a build script that builds our code:

```json
{
  "name": "emoji-search",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^2.3.2"
  },
  "dependencies": {
    "@types/emojione": "^2.2.1",
    "emojione": "^3.0.3"
  }
}
```

That’s all we have to do to configure the TypeScript project.  Let’s move on to writing some module code!

## ðŸ’» Create the module code

Create a `lib` folder where we can place all of our TypeScript files and in it create a create a file called `index.ts`. Place the following TypeScript into it:

```ts
import { toShort } from 'emojione';
const EMOJI_SHORTCODES = /:[a-zA-Z1-9_]+:/g
 
export function findEmojis(str: string): string[] {
  // add runtime check for use in JavaScript
  if (typeof str !== 'string') {
    return [];
  }
 
  return toShort(str).match(EMOJI_SHORTCODES) || [];
}
```

Compile the code by running:

```bash
npm run build
```

You should see a new `dist` directory that has two files, `index.js` and `index.d.ts`. The `index.js` contains all the logic that we coded compiled to JavaScript and `index.d.ts` is the file that describes the types of our module for use in TypeScript.

Congratulations on creating your first module accessible to both TypeScript and Javascript! Lets prep the module for publishing.

## ðŸ”– Prepare for publishing

Now that we have our module, we have to make three easy changes to the `package.json` to get ready to publish the module.

1. Change the `main` attribute to point at our generated JavaScript file
2. Add the new `types` parameter and point it to the generated TypeScript types file
3. Add a `prepublish` script to make sure that the code will be compiled before we publish the project.

```json
{
  "name": "emoji-search",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "prepublish": "npm run build",
    "build": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^2.3.2"
  },
  "dependencies": {
    "@types/emojione": "^2.2.1",
    "emojione": "^3.0.3"
  }
}
```

We should also make sure to exclude unnecessary files from the installation of our module. In our case the `lib/` folder is unnecessary because we only need the built files in the `dist/` directory. Create a new file called .npmignore and place the following content into it:

```txt
lib/
```

That’s it! ðŸŽ‰ You are ready now to publish your module using `npm publish`. Unfortunately someone already built a module called `emoji-search` ðŸ˜• so if you want to publish this module, just change the name in the `package.json` to another name.

## ðŸ½ Consume the module

The great thing with our module is that this can now be seamlessly used in JavaScript or TypeScript projects. Simply install it via `npm` or `yarn`:

```bash
npm install emoji-search --save
```

![decorative gif of flying emojis](https://www.twilio.com/blog/wp-content/uploads/2017/06/bzJAgsQpT5Yt33jc7geZ2lyT2J16paootSYAZcTiaHW6x2mLwaSnt1ks4cOoliUyhFY8cPIr3eIiY2LL3fEG7CE0Nryy03jGB64H-todm1cjAYhC9ULVdmnyUvmJFo0lfGhucuhV.png)

If you want to try this out without publishing the module yourself you can also install the `demo-emoji-search` module. It is the same code published on npm. Afterwards we can use the module in JavaScript:

```js
const emojiSearch = require('demo-emoji-search');
console.log(emojiSearch.findEmojis("Hello ðŸ¼! What's up? âœŒï¸"));
```

Or in TypeScript with full type support:

```ts
import { findEmojis } from 'demo-emoji-search';
const foundEmojis: string[] = findEmojis(`Hello ðŸµ! What's up? âœŒï¸`);
 
console.log(foundEmojis);
```

## ðŸŽŠ Conclusion

Now this was obviously just a very simple module to show you how easy it is to publish a module usable in both Javascript and TypeScript.

There are a boatload of other benefits provided by TypeScript to the author of the module such as:

- Better authoring experience through better autocomplete
- Type safety to catch bugs especially in edge cases early
- Down-transpilation of cutting-edge and experimental features such as decorators

As you’ve seen it’s very easy to build a module in TypeScript to provide a kickass experience with our module to both JavaScript and TypeScript developers. If you would like to have a more comprehensive starter template to work off that includes a set of best practices and tools, check out [Martin Hochel’s typescript-lib-starter on GitHub](https://github.com/Hotell/typescript-lib-starter).

âœŒï¸ I would love to hear about your experience with TypeScript and feel free to reach out if you have any problems:

- ðŸ“§ Email: dkundel@twilio.com
- ðŸ¦ Twitter: [@dkundel](https://twitter.com/dkundel)
- ðŸ–¥ GitHub: [dkundel](https://github.com/dkundel)

---

_[Writing a Node.js module in TypeScript](https://www.twilio.com/blog/2017/06/writing-a-node-module-in-typescript.html) was originally published on the [Twilio Blog](https://www.twilio.com/blog) on June 8, 2017._