简体   繁体   中英

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

I have looked everywhere for an answer to this question, but none of the other solutions have worked for me.

I get the following error:

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

SyntaxError: Cannot use import statement outside a module

When I try to run me compiled typescript code.

My 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"
},

And tsconfig.json :

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

I run npm run watch in the one terminal and the code compiles with zero errors. But when I run npm run start:dist in another terminal it throws that error.

Some other posts have mentioned that you need to add "type": "module" to package.json , but when I do that it throws this error:

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

ReferenceError: exports is not defined

Googling this error showed some answer that mention removing "module":"commonjs" from the tsconfig.json . When I do this it just complains that I have to add .js to all my imports which seems like the wrong thing to do.

I am pretty lost as to what to do so any help would be appreciated!

EDIT

Here is a repo with a minimal example: https://github.com/RiaanLaubscher/Soverflow

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

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