DEV Community

Cover image for Set up a Node.js project + TypeScript + Jest using ES Modules
Wagner Manganelli (aka manga)
Wagner Manganelli (aka manga)

Posted on • Updated on

Set up a Node.js project + TypeScript + Jest using ES Modules

TL;DR

In this tutorial, you will learn how to configure your Node.js app with TypeScript + Jest using ECMAScript modules (ESM).

What are ECMAScript modules?

ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements. - nodejs.org

As the description says, it is the official standard format. To know more about the differences and benefits there are plenty of articles talking about it. The intention here is to show you how to set up as smoothly as possible your app.


Let's set it up 🔧


Prerequisites

  • Node.js >= v18.12.0

Initial steps

mkdir app-esm
cd app-esm
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install dev dependencies

npm install --save-dev typescript@5.1.6 ts-node@10.9.1 ts-jest@29.1.1 jest@29.6.2 @types/jest@29.5.3
Enter fullscreen mode Exit fullscreen mode

Initialize TypeScript

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Set up project folder structure

app-esm/
├── __test__/
│   └── index.test.ts
├── src/
│   └── index.ts
├── jest.config.ts
├── package.json
└── tsconfig.json
Enter fullscreen mode Exit fullscreen mode

P.S. create manually jest.config.ts


Configuration steps

  • package.json
{
  ...
  "type": "module",
  "scripts": {
    "build": "tsc",
    "test": "node --experimental-vm-modules node_modules/.bin/jest",
    "start": "node dist/index.js"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode
  • tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "dist",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "./*.ts", "__test__"]
}
Enter fullscreen mode Exit fullscreen mode
  • jest.config.ts
import type { JestConfigWithTsJest } from "ts-jest";

const config: JestConfigWithTsJest = {
  verbose: true,
  transform: {
    "^.+\\.ts?$": [
      "ts-jest",
      {
        useESM: true,
      },
    ],
  },
  extensionsToTreatAsEsm: [".ts"],
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
};

export default config;
Enter fullscreen mode Exit fullscreen mode
  • That's it! Now you can start coding without bothering with the setup part. 🍺
P.S. you can refer to this template. There you will find some jest tests with mock examples.

Useful links


Tutorials that might interest you as well


I hope this tutorial helps you focus on what really matters.

Thank you for reading! Happy coding! 🥳

Top comments (0)