Wildcard erroring out on import in Node.js

Viewed 9

I keep getting an error on an import statement:

import * as foo from './bar.mjs'; 

Here is the code that I am testing...

import  *  as foo from './bar.mjs';

console.log(foo.hello());
console.log(`${foo.next()} ${foo.squared()}`);

console.log(`${foo.next()} ${foo.squared()}`);

console.log(`${foo.default()} ${foo.squared()}`);

console.log(`${foo.next()} ${foo.squared()}`);

console.log(`${foo.next()} ${foo.squared()}`);

console.log(`${foo.next()} ${foo.squared()}`);

console.log(foo.meaning);

Here is the error...

$ node testMod.mjs
/home/user/node-web-dev/testMod.mjs:1
import  *  as foo from './bar.mjs';
        ^

SyntaxError: Unexpected token *
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)    

Can anyone shed some light on why the wildcard '*' in the import statement is erroring out?

1 Answers

Node 10 requires the --experimental-modules argument to use the ESM module loader.

node --experimental-modules testMod.mjs
(node:80220) ExperimentalWarning: The ESM module loader is experimental.
[Module] { blah: 2, test: 1 }

The current versions of Node (16/18) have much better ESM support so I would start there.

Related