Node.js question concerning export and import

I am struggling with something that seems like it should work based on many articles I have read. However, it does not work.

I am doing this purely in Node.js and not using anything else.

Let’s say I have the following two files in the same folder:


export default function() { console.log("hello!") }


import foo from 'foo';
foo(); // expect hello to display in console

When I run importFoo.js using node importFoo or node importFoo.js I get the same error below:

$ node importFoo
(function (exports, require, module, __filename, __dirname) { import foo from 'foo';
SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

Just to let you know, I have also tried the following import statement in the importFoo.js file with a similar error.

import foo from './foo';

Can someone point me to some documentation which will explain what I am missing here? I am hoping it is something silly I am overlooking.

Thanks in advance.

It appears that import and export in node are still experimental although they are ES6 modules.

A thread here mentions

  1. Use a version of node that supports the –experimental-modules flag
  2. Your .js files must then be renamed to .mjs

Give the files an mjs extension and they should Just Work on newer versions of Node. There are some wierdnesses though, you can’t mix exports as far as I remember (eg module.exports will fail on an mjs file)

There are quite a lot of issues because import/export doesn’t work in the same way as require/module.exports - I had innumerable problems trying to build an Express app, particularly when I tried to use a bin script to start it

Edit: I know .mjs is a transitory solution, and the Node folks didnt really have any other option because CommonJS is so welded into the way the platform works, but it’s pretty painful to use, tho ymmv