I want to use both typescript and the es6 module in my Node.js project, and in addition, I want the files compiled to the javascript language to have the es6 module.
This is my package.json :
{
"name": "arep",
"version": "1.0.0",
"description": "",
"main": "app.ts",
"type": "module",
"scripts": {
"start": "nodemon --exec ts-node app.ts",
"build": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.1",
"express": "^4.18.2",
"mysql2": "^3.9.1"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^20.11.17",
"nodemon": "^3.0.3",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
}
And this is my tscongif.json :
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
Here is the error I get :
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/rznkolds/Desktop/Standart/2- Development/2- Applications/1- NodeJS/arep/app.ts
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
at defaultLoad (node:internal/modules/esm/load:141:22)
at async nextLoad (node:internal/modules/esm/hooks:865:22)
at async nextLoad (node:internal/modules/esm/hooks:865:22)
at async Hooks.load (node:internal/modules/esm/hooks:448:20)
at async handleMessage (node:internal/modules/esm/worker:196:18) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
When I do this with the commonjs module, everything works fine, but when I do it with the es6 module, I get this error.
I couldn’t find much resources about this error. In many places, people solved the problem by turning it into the CommonJS module.