Search code examples
node.jses6-modules

Node.js Bug Or Am I Doing it Wrong? ES Modules


I am using the latest Node version 16.16.0, and in my project's package.json I have:

"type": "module",

That should enable ES Module (ie. import) syntax. However, when I try to run any file:

node some/path/file.js

I get:

> (node:1358624) 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/me/project/some/path/file.js:1
> import { test } from 'ava';
> ^^^^^^
> 
> 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 Object.Module._extensions..js (node:internal/modules/cjs/loader:1159: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

In other words, Node seems to be ignoring my package.json and treating the project like a CommonJS one ... even though I have:

"type": "module",

Is this a bug in Node, or is there any way I could somehow be accidentally telling Node "switch back to CommonJS"? I would very much prefer not to have to rename every one of my files to .mjs.

EDIT: For those asking about my package.json file. It (obviously) has a bunch of stuff in it, but even if I reduce it to *just:

{
  "type": "module",
}

I still have the issue.

EDIT #2: I don't understand the votes to close. There's a clear question here:

Is this a bug in Node, or is there any way I could somehow be accidentally telling Node "switch back to CommonJS"?

And all of the information necessary to answer it is provided. You don't need any specific package.json, you simply need to know that sub-directory package.json files trump parent-directory ones (and thus that one could "tell node to switch back" by having a sub-directory file).


Solution

  • The issue wound up being something really stupid ...

    I had (another) package.json file in the file's subdirectory!

    Originally I had asked:

    is there any way I could somehow be accidentally telling Node "switch back to CommonJS"?

    It turned out, there was! The package.json that was in the directory closer to the file being run took precedence over the project's package.json.