Node.js – SyntaxError: Cannot use import statement outside a module

Node.js

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.

How to reproduce it

tsconfig.json

        "module": "ESNext",
        "outDir": "./dist/js",
        "target": "esnext",

Run app

node index.js

Error

[nodemon] starting `node dist/js/testcases/index.js`
(node:10178) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/matej/Documents/Development/TypeScript/dist/js/testcases/index.js:1
import { run } from './imports';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:827:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v18.3.0
[nodemon] app crashed - waiting for file changes before starting...

Solution

Update tsconfig.json file – change module type to CommonJS.

        "module": "CommonJS",
        "outDir": "./dist/js",
        "target": "esnext",
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Comments are closed.