Initialize and Install Typescript
npm init -y
npm install -D typescript @types/node
Update the package.json
with a build script and change the type to module.
{
"type": "module",
"scripts": {
"build": "tsc"
},
}
Create a tsconfig.json
file and use the NodeNext
option to handle ES Modules with interop between CommonJS modules.
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"sourceMap": true,
"outDir": "dist",
},
"include": ["src/**/*"],
}
Use ES Modules
//hello.ts
export const hello = 'Hello World!';
//index.ts
import { hello } from './hello.js';
Use CommonJS Modules
//hello.cts
module.exports = 'Hey!';
//index.ts
import hola from './hello.cjs';
Next run
npm run build
node dist/index.js
Top comments (0)