Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
How to use import with existing Node app?

With Node 16.13.2 I am trying to add the validate module in an existing code base. Reading the 2 year old question I can't make it work with the below PoC. I get

import Schema from 'validate';
^^^^^^
SyntaxError: Cannot use import statement outside a module

Question

Can anyone show me how the below PoC should look like for it to work?

index.js

const mod = require('./mod');

mod.js

import Schema from 'validate';

const test;
module.exports = test;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you want to use the import syntax of es6+ then you will either need to use .mjs files (instead of regular .js files), or you will need to add in a compilation/transpilation step into your pipeline.

Using .mjs

If you change the file name of your mod.js file to mod.mjs, then this should work:

import Schema form 'validate';
export const test;

Then in index.js you will either have to change index.js to index.mjs and change the contents to:

import { test } from './mod.mjs';

..or you can keep index.js and change the contents to:

(async () {
  const { test } = await import('./mod.mjs')
})();

You can read more in this rather comprehensive article i happened across while googling: https://blog.logrocket.com/how-to-use-ecmascript-modules-with-node-js/

Adding a compilation step

There are many different compilers and/or bundlers to pick from, but for regular vanilla javascript I'd recommend sticking to babel.

Freecodecamp has a tutorial for how to set up babel for use with nodejs: https://www.freecodecamp.org/news/setup-babel-in-nodejs/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda