I was running into this issue with Node 18 with a single file src/index.js
that uses import
statements, here's the error message I got:
(node:13859) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node-18 --trace-warnings ...` to show where the warning was created)
[...redacted...]src/index.js:5
import { createServer } from 'node:http'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1178:20)
at Module._compile (node:internal/modules/cjs/loader:1220:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
at node:internal/main/run_main_module:23:47
The only things I had to do to resolve this was rename my src/index.js
to src/index.mjs
and start it with the command node src/index.mjs
(node src
finds index.js but not index.mjs
). Happy day:
$ node src/index.mjs
Server is running on http://localhost:8080