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
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
Initialize TypeScript
npx tsc --init
Set up project folder structure
app-esm/
├── __test__/
│ └── index.test.ts
├── src/
│ └── index.ts
├── jest.config.ts
├── package.json
└── tsconfig.json
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"
},
...
}
- tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "./*.ts", "__test__"]
}
- 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;
- 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
- Node.js ECMAScript Modules
- Typescript ECMAScript Module Support
- Jest ECMAScript Modules
- TS Jest ECMAScript Module Support
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 (2)
Truly want to say thanks for this. Saved me hours of time! Keep it up!
this saved my life 🙏