繁体   English   中英

运行编译的 Javascript 代码时,TypeScript 文件中出现“语法错误:无法在模块外使用导入语句”错误

[英]"SyntaxError: Cannot use import statement outside of a module" error in a TypeScript file when running compiled Javascript code

我到处寻找这个问题的答案,但没有其他解决方案对我有用。

我收到以下错误:

D:\some\path\User.model.ts:11
import { Field, ID, InterfaceType, ObjectType } from "type-graphql";
^^^^^^

SyntaxError: Cannot use import statement outside a module

当我尝试运行我编译的打字稿代码时。

我的package.json

"scripts": {
  "start:dist": "nodemon ./dist/app.js",
  "start:dev": "tsnd --respawn --no-notify ./src/app.ts",
  "build": "rimraf ./dist && tsc",
  "watch": "tsc -w",
  "db:setup:test": "tsnd ./src/test-utils/setup",
  "test": "npm run db:setup:test && jest"
},

tsconfig.json

"target": "ES6",
"module": "commonjs",

我在一个终端中运行npm run watch并且代码编译时错误为零。 但是当我在另一个终端中运行npm run start:dist ,它会抛出该错误。

其他一些帖子提到您需要将"type": "module"package.json ,但是当我这样做时,它会引发此错误:

file://path/to/file/app.js:14
Object.defineProperty(exports, "__esModule", {value: true});

ReferenceError: exports is not defined

谷歌搜索这个错误显示了一些提到从"module":"commonjs"删除"module":"commonjs"tsconfig.json 当我这样做时,它只是抱怨我必须将.js添加到我所有的导入中,这似乎是错误的做法。

我不知道该怎么做所以任何帮助将不胜感激!

编辑

这是一个带有最小示例的存储库: https : //github.com/RiaanLaubscher/Soverflow

我也遇到了这个问题,问题是我的 package.json 文件中有一个"type"="module"字段,删除该字段后它对我来说很好用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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