简体   繁体   中英

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 (ie 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

Try adding the line below to your package.json .

"type": "module",

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM