Rachit Aryal
Rachit Aryal

Reputation: 1

TypeScript: Cannot use import statement outside a module (Node.js)

I've been developing a package in node using typescript. When I install the package locally (i.e. providing the local path to the directory of the package, $ npm install ../my_package) everything works fine.

But I've published the package in npm and now when I install the same package from npm it shows me the above-mentioned error:

Cannot use import statement outside a module

I could not find a solution to my problem anywhere. I would really appreciate it if anyone could help me out here.

Error Msg Image

Upvotes: 0

Views: 1789

Answers (2)

Rachit Aryal
Rachit Aryal

Reputation: 1

If anyone is having the same problem while developing in typescript here's how I solved it.

If you don't already have tsconfig.json file you can create one by $ tsc --init.

Add the following to the tsconfig.json:

"declaration": true,
"outDir": "./dist",
"rootDir": "./",

In your package.json file add

"types": "dist/index.d.ts",
"main": "dist/index.js",

Compile the project with $ tsc.

Ps: in the .gitignore file add node_modules and /dist. Now publish it using $npm publish.

Upvotes: 0

Iman
Iman

Reputation: 1297

Try adding the line below to your package.json.

"type": "module",

Upvotes: 1

Related Questions