0

Exact same ask as SyntaxError: Cannot use import statement outside a module, but much simplified to focus on one specific aspect of the problem.

So, if I'm writing my nodejs based apps, is it really so that I cannot use the new EMS import statements there?

Here is the extremely simplified version of my nodejs based app (index.js):

import Database from 'better-sqlite3';
const db = new Database('foobar.db', options);

Here is what I get:

(node:1) 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)
/app/index.js:1
import Database from 'better-sqlite3';
^^^^^^

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

I do want to load the ES module using the new EMS import syntax, but I'm not writing a module myself, but an app instead. Thus I feel wrong to put "type": "module" in the package.json or use the .mjs extension, which stresses that its an ES module.

It just doesn't feel right -- nobody has called an express web application a module before.

E_net4
  • 27,810
  • 13
  • 101
  • 139
xpt
  • 20,363
  • 37
  • 127
  • 216
  • 1
    It's not denoting that you're writing a module, but that you're using ES modules. https://nodejs.org/api/packages.html#determining-module-system – Phix Feb 23 '22 at 16:36
  • Oh, to differentiate from `CommonJS`. Gotcha @Phix, thx! – xpt Feb 23 '22 at 16:38
  • 1
    Just install the esm package and require it before running your code. It lets you use CommonJS and imports/exports syntax without needing to compile it using babel or something. ```npm install esm``` and to run your code ```node -r esm index.js``` – Abir Taheer Feb 23 '22 at 16:44

0 Answers0