Bishonen_PL
Bishonen_PL

Reputation: 1571

Generating index.js files exporting all (thousands) components

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?

Upvotes: 4

Views: 669

Answers (3)

JordyJordyJordyJordan
JordyJordyJordyJordan

Reputation: 147

Vincius's answer works excellently, but it leaves the file extension on it. We don't want that in react imports.

Here's a modified version:

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

edit: expanding it a little further:

echo -n > index.tsx
for f in *.tsx; do
if  [ $f != "index.tsx" ]; then
  echo "export { default as ${f%.*} } from './${f%.*}'" >> index.tsx
  fi
done

This will additionally

  1. clear the current index file if it exists
  2. not include the file "index.tsx", which it normally would do since it's included in the directory.

Note: You'll have to CD into the specific directory.

Upvotes: 1

NearHuscarl
NearHuscarl

Reputation: 81410

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

Upvotes: 1

Vinicius Katata
Vinicius Katata

Reputation: 1051

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

Upvotes: 2

Related Questions