I have many different modules in a project, each module has it's own folder, within each module, there are 3 files:
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?
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);