How to correctly use import in Node JS

Viewed 886

I added "type": "module" to package.json. I was under the impression no translation between ES6 and CommonJS was necessary with the newer versions of node to use import, in this case v16.0.0.

What do I need to change to get import to work?


I have 3 simple files in the same directory.

  1. package.json
  2. main.js
  3. Utility.js

package.json

{
  "name": "node_template",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "type": "module"
}

Utility.js

'use strict';

class Utility {
   constructor() {
   }
}

export { Utility };

main.js

"use strict";

(async ()=>{
    import { Utility } from './Utility.js';
    var utility = new Utility();
    console.log( "Main" );
})();

When I run "node main.js" I get the following error:

node -v
v16.0.0

node main.js

main.js:4
    import { Utility } from './Utility.js';
           ^
SyntaxError: Unexpected token '{'
←[90m    at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m    at async link (node:internal/modules/esm/module_job:64:21)←[39m
1 Answers
Related