Generating index.js files exporting all (thousands) components

Viewed 217

when looking into libraries such as material-ui, it becomes quite clear that there's some sort of script which takes care of exporting thousands of components at the same time from an index.js file.

If we look e.g. here, I can only assume that this file wasn't generated by a person (8k+ exports).

Before I reinvent the wheel, is there some standard library that one uses to create those export files? Or does rollup or some other bundler create them on the fly?

2 Answers

This shell should do the work

for f in *.js; do
  echo "export { default as $f } from './$f'"
done

Redirect the output to a file and that's it

They export all icon components using a custom script called builder.js. This script is run when you execute this command: npm run src:icons. Here is the relevant part.

async function generateIndex(options) {
  const files = await globAsync(path.join(options.outputDir, '*.js'));
  const index = files
    .map((file) => {
      const typename = path.basename(file).replace('.js', '');
      return `export { default as ${typename} } from './${typename}';\n`;
    })
    .join('');

  await fse.writeFile(path.join(options.outputDir, 'index.js'), index);
}

options.outputDir is the directory that contains all component files, in this case packages/material-ui-icons/src

Related