Skip to content

Commit

Permalink
handle multi-component objects and ambiguous package paths
Browse files Browse the repository at this point in the history
  • Loading branch information
jskrzypek committed May 21, 2018
1 parent b75b624 commit 97f6339
Showing 1 changed file with 32 additions and 10 deletions.
42 changes: 32 additions & 10 deletions packages/mjml-core/src/helpers/mjmlconfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,14 +21,45 @@ 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 => {
const resolvedPath = resolveComponentPath(compPath, componentRootPath)
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
Expand Down

0 comments on commit 97f6339

Please sign in to comment.