From 97f6339fb2f7fea4b835cf0639119bad6a586a8c Mon Sep 17 00:00:00 2001 From: Joshua Estrin Skrzypek Date: Mon, 21 May 2018 14:55:05 +0300 Subject: [PATCH] handle multi-component objects and ambiguous package paths --- packages/mjml-core/src/helpers/mjmlconfig.js | 42 +++++++++++++++----- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/packages/mjml-core/src/helpers/mjmlconfig.js b/packages/mjml-core/src/helpers/mjmlconfig.js index 4c5d4e68a..f667ffd50 100644 --- a/packages/mjml-core/src/helpers/mjmlconfig.js +++ b/packages/mjml-core/src/helpers/mjmlconfig.js @@ -3,15 +3,6 @@ import fs from 'fs' import { registerComponent } from '../components' -export function resolveComponentPath(compPath, componentRootPath) { - if (!compPath) { - return null - } else if (compPath.startsWith('.') || path.isAbsolute(compPath)) { - return path.resolve(componentRootPath, compPath) - } - return require.resolve(compPath) -} - export function readMjmlConfig(configPathOrDir = process.cwd()) { let componentRootPath = process.cwd() let mjmlConfigPath = configPathOrDir @@ -30,6 +21,37 @@ export function readMjmlConfig(configPathOrDir = process.cwd()) { } } + +export function resolveComponentPath(compPath, componentRootPath) { + if (!compPath) { + return null + } + if (!compPath.startsWith('.') && !path.isAbsolute(compPath)) { + try { + return require.resolve(compPath) + } catch (e) { + if (e.code !== 'MODULE_NOT_FOUND') { + console.log('Error resolving custom component path : ', e) // eslint-disable-line no-console + return null + } + // if we get a 'MODULE_NOT_FOUND' error try again with relative path: + return resolveComponentPath(`./${compPath}`, componentRootPath) + } + } + return require.resolve(path.resolve(componentRootPath, compPath)) +} + +export function registerCustomComponent(comp, registerCompFn = registerComponent) { + if (comp instanceof Function) { + registerCompFn(comp) + } else { + const compNames = Object.keys(comp) // this approach handles both an array and + compNames.forEach(compName => { + registerCustomComponent(comp[compName], registerCompFn) + }) + } +} + export default function registerCustomComponents(configPathOrDir = process.cwd(), registerCompFn = registerComponent) { const { mjmlConfig: { packages }, componentRootPath } = readMjmlConfig(configPathOrDir) packages.forEach(compPath => { @@ -37,7 +59,7 @@ export default function registerCustomComponents(configPathOrDir = process.cwd() if (resolvedPath) { try { const requiredComp = require(resolvedPath) // eslint-disable-line global-require, import/no-dynamic-require - registerCompFn(requiredComp.default || requiredComp) + registerCustomComponent(requiredComp.default || requiredComp, registerCompFn) } catch (e) { if (e.code !== 'ENOENT') { console.log('Error when registering custom component : ', resolvedPath, e) // eslint-disable-line no-console