0

Consider following file structure of JavaScript files of a redux project (which is not that important but it's a real life scenario):

plugins/
  a/reducer.js
  b/reducer.js
  c/reducer.js
  rootReducer.js

This is the current content of rootReducer.js:

import { combineReducers } from 'redux'
import a from './a/reducer'
import b from './b/reducer'
import c from './c/reducer'

export default combineReducers({ a, b, c });

Note that each of the reducer.js files default exports a reducer function.

To add a new plugin, I create an appropriate folder, add a new reducer.js file to it and then I need to manually import the reducer file and register it in rootReducer.js.

I would like this process to be fully automatic. I want the rootReducer.js file to go through all the subdirectories, look for a file reducer.js inside of them and eventually import it and add it to the root reducer using the folder name.

I'm using webpack and babel to compile and bundle my JavaScript files.

I know that there is a file system API in Node.js which would allow me to iterate through the folders and look for the reducer.js file. But is it going to work correctly once bundled with webpack? Is it safe to dynamically import modules/files?

tobik
  • 7,098
  • 7
  • 41
  • 53

1 Answers1

0

You could do something similar to the following

'use strict';

const fs = require('fs');
const DIR = __dirname + '/plugins';
const output = __dirname + '/plugins/rootReducer.js';

return fs.readdir(DIR, (err, files) => {
  let result = `import { combineReducers } from 'redux'\n`;
  let references = [];
  let reducers = files.filter(a => !a.includes('.'));

  reducers.forEach(reducer => {
    references.push(reducer);
    result += `import ${reducer} from './${reducer}/reducer'\n`;
  });

  result += `\nexport default combineReducers({ ${references} });\n`;
  fs.writeFile(output, result, err => {
    if(err) throw err;
    console.log(output + ' updated');
  });
});

Place this in your project directory and name it whatever you'd like. I'll call it reducersScript.js

From here you can either run it with node manually node reducersScript.js or hook it into your build process.

Koblinski
  • 61
  • 1
  • 9