In the server directory of my web app (in TypeScript), I have a nodemon
command (that reruns code after changes) like this:
nodemon dist/index.js
However, running it now throws this error:
/path/to/app/server/src/entities/Post.ts:1
import { Field, Int, ObjectType } from "type-graphql";
^^^^^^
SyntaxError: Cannot use import statement outside a module
From what I read on here, the cause of this error is typically the fact that Node.js requires CommonJS syntax by default (as in this question, for example).
In my tsconfig.json
, I have these compilerOptions
:
"target": "es2017",
"module": "commonjs",
"moduleResolution": "node",
"lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
"skipLibCheck": true,
(In my package.json
, "type"
is not specified.)
In tsconfig.json
, "module"
is specified as "commonjs"
, and it seems that tsc
compiles JavaScript correctly. Running tsc
gives me no errors, and the same file in /dist
uses exports
syntax (Object.defineProperty(exports, "__esModule", { value: true });
, for example), which is correct CommonJS syntax, right?
Running the same nodemon
command with ts-node
doesn't return any errors:
nodemon --exec ts-node src/index.ts
What's interesting, I only started getting this error after initializing a Docker build in my /server
like this:
docker build -t [username]/[project]:[version] .
Any attempts to get Node to use ES (setting "type": "module"
in package.json
and changing "module"
only seem to bring more errors. (I was regenerating /dist
to make sure it's not caused by older compiled files.)
Versions:
tsc
: 4.9.5
node
: 18.13.0
nodemon
: 2.0.20
What am I doing wrong here?
Any help would be much appreciated!
Hmmm I'm going to take a bit of an educated guess. What's strange is from your error you appear to have /path/to/app/server/src/entities/Post.ts
(notice the ts extension and the fact the path is coming from src and not dist) being imported and yet you are running a js file from dist. Technically you should only see .js files being imported. My suspicion is you are somehow importing src/entities/Post.ts incorrectly. For example you could be doing something along the lines of ../src/entities/Post.ts
which would break out of dist and make it into src. Regardless the point is somehow you are importing Post.ts from src and not dist.
This would also explain why running from ts-node works, but running from ./dist/index.js does not. Feel free to leave a comment here so I can help you debug this further if it's not clear what you are supposed to do next.