Setting Up Nodejs with Typescript

Manthan Ankolekar - Jan 4 '23 - - Dev Community

Initialize and Install Typescript

npm init -y
npm install -D typescript @types/node
Enter fullscreen mode Exit fullscreen mode

Update the package.json with a build script and change the type to module.

{
  "type": "module",
  "scripts": {
    "build": "tsc"
  },
}
Enter fullscreen mode Exit fullscreen mode

Create a tsconfig.json file and use the NodeNextoption to handle ES Modules with interop between CommonJS modules.

{
    "compilerOptions": {
      "module": "NodeNext",
      "moduleResolution": "NodeNext",
      "target": "ES2020",
      "sourceMap": true,
      "outDir": "dist",
    },
    "include": ["src/**/*"],
  }
Enter fullscreen mode Exit fullscreen mode

Use ES Modules

//hello.ts
export const hello = 'Hello World!';

//index.ts
import { hello } from './hello.js';
Enter fullscreen mode Exit fullscreen mode

Use CommonJS Modules

//hello.cts
module.exports = 'Hey!';

//index.ts
import hola from './hello.cjs';
Enter fullscreen mode Exit fullscreen mode

Next run

npm run build
node dist/index.js
Enter fullscreen mode Exit fullscreen mode

Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .