[英]TypeScript: Cannot use import statement outside a module (Node.js)
I've been developing a package in node using typescript.我一直在使用 typescript 在节点中开发 package。 When I install the package locally (ie providing the local path to the directory of the package,
$ npm install../my_package
) everything works fine.当我在本地安装 package 时(即提供 package 目录的本地路径,
$ npm install../my_package
)一切正常。
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: 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.
如果有人可以在这里帮助我,我将不胜感激。
Try adding the line below to your package.json
.尝试将下面的行添加到您的
package.json
。
"type": "module",
If anyone is having the same problem while developing in typescript here's how I solved it.如果有人在 typescript 开发时遇到同样的问题,这就是我解决它的方法。
If you don't already have tsconfig.json file you can create one by $ tsc --init
.如果您还没有 tsconfig.json 文件,您可以通过
$ tsc --init
创建一个。
Add the following to the tsconfig.json:将以下内容添加到 tsconfig.json:
"declaration": true,
"outDir": "./dist",
"rootDir": "./",
In your package.json file add在您的 package.json 文件中添加
"types": "dist/index.d.ts",
"main": "dist/index.js",
Compile the project with $ tsc
.使用
$ tsc
编译项目。
Ps: in the .gitignore
file add node_modules
and /dist
. ps:在
.gitignore
文件中添加node_modules
和/dist
。 Now publish it using $npm publish
.现在使用
$npm publish
发布它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.