I am beginner in typescript and currently learning it. I came across a problem in importing and exporting a custom function (that i made). So basically, what i did is i made index.ts file and write this code:
export function sayHi(): void {
console.log("Hiiii!");
}
and then i made another file (file2.ts) and wrote this code:
import {sayHi} from './index.js';
sayHi();
Now, this code is working perfectly fine… (without tsconfig and package.json files).
Then, I had to install inquirer so i created tsconfig file using this command:
tsc init
after creating my tsconfig file in the directory, the code is still working perfectly fine…
MY tsconfig file:
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
but when i created my package.json file using:
npm init --yes
then, its giving me error:
D:CoursesGI-AIWMDProgrammingPractice2>node file2.js
file:///D:/Courses/GI-AIWMD/Programming/Practice2/file2.js:2
Object.defineProperty(exports, "__esModule", { value: true });
^
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a ‘.js’ file extension and ‘D:CoursesGI-AIWMDProgrammingPractice2package.json’ contains "type": "module". To treat it as a CommonJS script, rename it to use the ‘.cjs’ file extension.
at file:///D:/Courses/GI-AIWMD/Programming/Practice2/file2.js:2:23
at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
at async loadESM (node:internal/process/esm_loader:34:7)
at async handleMainPromise (node:internal/modules/run_main:113:12)
Node.js v20.10.0
My package.json file:
{
"name": "practice2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type":"module",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Note: i tried setting type: commonjs, its working fine then code is running but i cannot use inquirer package then, so i cannot set type to commonjs, it should remain type: module…
2
Answers
Ok so, someone told me that i was transpiling files with command: tsc index.ts file2.ts, so it was giving me error.. when i transpiled with tsc (only), then its running properly.
Follow the below steps:
for module import install npm install @types/node –save-dev