Skip to content

Instantly share code, notes, and snippets.

@willdavidow
Last active May 6, 2017 14:34
Show Gist options
  • Save willdavidow/c8e77dd001d8b874754c35d44b4569a0 to your computer and use it in GitHub Desktop.
Save willdavidow/c8e77dd001d8b874754c35d44b4569a0 to your computer and use it in GitHub Desktop.
// Array merge function. Credit: Kyle Simpson - https://github.com/getify. Link: https://davidwalsh.name/combining-js-arrays
export const arrayMerge = (head, tail) => {
return tail.reduce( (coll, item) => {
coll.push(item);
return coll;
}, head);
};
import fs from 'fs';
import path from 'path';
import { arrayMerge } from './array.utils';
function componentPaths(itemPath, componentFolder = 'components') {
const cwd = fs.readdirSync(itemPath).map((item) => {
if (fs.existsSync(`${itemPath}/${item}/${componentFolder}`)) {
componentPathArray = arrayMerge(componentPathArray, componentPaths(`${itemPath}/${item}/${componentFolder}`));
}
return path.resolve(itemPath, item);
});
return cwd;
}
export const componentTree = (srcPath) => {
let componentPathArray = [];
const rootPaths = componentPaths(srcPath);
return arrayMerge(rootPaths, componentPathArray);
};
@willdavidow
Copy link
Author

willdavidow commented May 6, 2017

Usage:

import { componentPaths } from './webpack.utilities';
var componentDirs = componentPaths('./src/components');

Given the following folder structure:

src
├── components
│   ├── SomeComponent
│   │   ├── SomeComponent.jsx
│   ├── AnotherComponent
│   │   ├── AnotherComponent.jsx
│   ├── ComponentWithNestedComponents
│   │   ├── components
│   │   │   ├── NestedComponent
│   │   │   │   ├── NestedComponent.jsx
│   │   ├── ComponentWithNestedComponents.jsx

Expected output would be:

componentDirs = [
   'src/components/SomeComponent',
   'src/components/AnotherComponent',
   'src/components/ComponentWithNestedComponents',
   'src/components/ComponentWithNestedComponents/components/NestedComponent'
];

I've found this useful with webpack's resolve.modules config, which allows me to spread ...componentDirs into that config and include modules with little/no repetition.

Example (using the folder structure above):

import SomeComponent from './components/SomeComponent/SomeComponent';

becomes:

import SomeComponent from 'SomeComponent';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment