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 };
jesugmz
  • 2,320
  • 2
  • 18
  • 33
  • 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. – str Jan 17 '20 at 16:36
  • You are right @str. My previous comment did not appear :/ Thanks! – jesugmz Jan 17 '20 at 17:33

1 Answers1

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;

Michael
  • 581
  • 2
  • 8