0

I'm experimenting with ECMAScript modules in Node.js 12 but I'm struggling with. Following the official docs just by adding the top-level field "type" with a value of "module" it should be enough to keep using the extension .js in this Node.js version but I can not find why is not working as expected. Am I missing something?

$ node --version
v12.14.1
$ cat package.json 
{
  "type": "module",
  "scripts": {
    "start": "node test.js"
  }
}
$ npm start

> app@ start /usr/src/app
> node test.js

/usr/src/app/test.js:1
import { myFunction } from './module.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11
$ cat test.js
import { myFunction } from './module.js';

myFunction();
$ cat module.js 
function myFunction() {
  console.log('hello from module');
}

export { myFunction };
2
  • 3
    You are using Node.js 12 but reading the documentation of Node.js 13. Edit: Now that you link to the proper documentation, you do not use the --experimental-modules flag as stated in the docs. Commented Jan 17, 2020 at 16:36
  • You are right @str. My previous comment did not appear :/ Thanks! Commented Jan 17, 2020 at 17:33

1 Answer 1

1

https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_code_import_code_statements

Version 12 docs for that import statement show that you can only import the default export via import ... from ...

So import myFunction from './module.js'; would work if you exported myFunction as export default myFunction;

Sign up to request clarification or add additional context in comments.

2 Comments

That only affects "CommonJS files or packages", not ESM as in the question.
Also worth noting that this is how it works in previous versions of node as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.