Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

778
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda