Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

781
Views
How to correctly use import in Node JS

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
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

main.js

(async () => { 
let { Utility } = await import('./Utility.js');
let utility = new Utility();
console.log('main');
})();

Note: The import statement you used, should only be used at top-level of the module. But you can dynamically or conditionally import module by using dynamic import - import(). See the links below for more detail.

Links:

https://v8.dev/features/dynamic-import

https://flaviocopes.com/javascript-dynamic-imports/

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!