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

316
Visualizações
Is there a way to consolidate the imports/requires into one line in javascript?

I have many different modules in a project, each module has it's own folder, within each module, there are 3 files:

  • index.js
  • index.test.js
  • data.js

Every module has these files, same file names and different content.

For the index.test.js files, the import statements are all the same for all index.test.js files in all modules, look like this:

const runAnalysis = require('./index');
const { data } = require('./data');
const { formatData } = require('utils');
const formattedData = formatData(data);

Since these import statements are the same for all index.test.js files, is there a way to consolidate these into one line, so it doesn't have to be repeated over and over in every module?

Is there a way to put these import statements in a header file, and then each index.test.js can just import the header file?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Not sure if this is efficient or recommended, but it works.

Create a util js file and it can live at the project root directory, let's name it import-util.js with the following code.

const { formatData } = require('utils');

const getMyImports = (dirname) => {
  const runAnalysis = require(`${dirname}/index`);
  const { data } = require(`${dirname}/data`);
  const formattedData = formatData(data);
  
  return {
    runAnalysis,
    formattedData
  }  
};

exports.getMyImports = getMyImports;

Then this file can be used like this to get the runAnalysis and formattedData

const { runAnalysis, formattedData } = require('../import-util').getMyImports(__dirname);

__dirname is the trick to make it work, it provides the directory path for the index.js and data.js to be imported.

This single line can now be used in every module folder, given the folder contains the index.js and data.js, it works the same as the following 4 lines of code.

const runAnalysis = require('./index');
const { data } = require('./data');
const { formatData } = require('utils');
const formattedData = formatData(data);
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