Skip to content

Use cases

Conrad Buck edited this page Mar 19, 2022 · 3 revisions

Here are some ideas about things you could use macrome to do:

Create a directory index:

Suppose you have a routes folder containing files each of which define a route in your application. You wish to ensure that all routes that are defined are registered centrally with a router. You want to be able to write this:

import router from 'some-router';
import * as routes from './routes/index.js';

router.registerRoutes(routes);

You need an index file though that exports all the routes, which will look something like this:

export {default as foo} from './foo.js';
export {default as bar} from './bar.js';

If you've worked with index files like these you'll know that keeping them up to date is not a major inconvenience, but it isn't wholly without potential trip-ups either. Novice contributors may not know where to add files they create. The files may lose their alphabetical order making it harder to know what is or is not present. Debugging modifications might get checked in by accident! This adds up to one more thing to think about and distract from other work. Instead, we can write a simple macrome generator that solves all these problems for us!

const {basename} = require('path');

module.exports = {
  include: ['routes/*.js'],

  async reduce(api, mappings) {
    await api.write(
      'routes/index.js',
      [...mappings.keys()]
        .sort()
        .map(path => `export {default as ${basename(path, '.js')} from './${basename(path)}';`)
        .join('\n')
    );
  }
}
Clone this wiki locally