2018-03-22 20:45:03 +01:00
|
|
|
const { customComponents } = require('../../config/siteConfig.js');
|
2018-03-20 20:23:39 +01:00
|
|
|
|
|
|
|
function getDeepestChildValue (parent, childrenKeys) {
|
|
|
|
let childKey = childrenKeys.shift(); // .shift() retrieves the first element of array and removes it from array
|
|
|
|
let child = parent[childKey];
|
|
|
|
if (childrenKeys.length >= 1) {
|
|
|
|
return getDeepestChildValue(child, childrenKeys);
|
|
|
|
}
|
|
|
|
return child;
|
|
|
|
}
|
|
|
|
|
2018-03-20 21:20:15 +01:00
|
|
|
export const dynamicImport = (filePath) => {
|
2018-03-20 20:23:39 +01:00
|
|
|
// validate inputs
|
|
|
|
if (!filePath) {
|
|
|
|
throw new Error('no file path provided to dynamicImport()');
|
|
|
|
}
|
2018-03-20 21:31:00 +01:00
|
|
|
if (typeof filePath !== 'string') {
|
2018-03-20 21:26:52 +01:00
|
|
|
console.log('dynamicImport > filePath:', filePath);
|
2018-03-20 21:31:00 +01:00
|
|
|
console.log('dynamicImport > filePath type:', typeof filePath);
|
2018-03-20 20:23:39 +01:00
|
|
|
throw new Error('file path provided to dynamicImport() must be a string');
|
|
|
|
}
|
2018-03-22 20:45:03 +01:00
|
|
|
if (!customComponents) {
|
2018-03-20 21:37:34 +01:00
|
|
|
return require(`${filePath}`);
|
|
|
|
}
|
2018-03-20 20:23:39 +01:00
|
|
|
// split out the file folders // filter out any empty or white-space-only strings
|
|
|
|
const folders = filePath.split('/').filter(folderName => folderName.replace(/\s/g, '').length);
|
|
|
|
// check for the component corresponding to file path in the site config object
|
2018-03-22 20:45:03 +01:00
|
|
|
// i.e. customComponents[folders[0]][folders[2][...][folders[n]]
|
|
|
|
const component = getDeepestChildValue(customComponents, folders);
|
|
|
|
if (component) {
|
|
|
|
return component; // return custom component
|
2018-03-20 20:23:39 +01:00
|
|
|
} else {
|
2018-03-20 21:20:15 +01:00
|
|
|
return require(`${filePath}`);
|
2018-03-20 20:23:39 +01:00
|
|
|
}
|
|
|
|
};
|