Skip to content

Instantly share code, notes, and snippets.

@cusspvz
Created November 14, 2016 15:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cusspvz/f77f5a0e3fb201c9816f33cad6274cfd to your computer and use it in GitHub Desktop.
Save cusspvz/f77f5a0e3fb201c9816f33cad6274cfd to your computer and use it in GitHub Desktop.
require-by-kind
const PREFIX = 'synaptic'
const NpmRegExp = /^@?[a-z0-9\-]*([a-z0-9\-])?$/
export default function requireByKind ( kind, given ) {
// Avoid access to specific files by restricting the `given`
if ( given.match( NpmRegExp ) ) {
throw new Error( `only alphanumeric names are valid` )
}
const possibilities = [
`./${kind}/${given}`,
`${PREFIX}-${kind}-${given}`,
`${PREFIX}-${given}`,
`${given}`
]
let kindModule
for ( let possibility of possibilities ) {
try {
return require( possibility )
} catch ( e ) {
// Going to loop again
}
}
// If the loop ends, we didn't found the module
throw new Error( `Please check if the given ${kind} module is installed` )
}
// Example:
// Forms to load up the module: synaptic-backend-web-worker
requireByKind( 'plugin', 'web-worker' )
// Would require this possibilities
// ./plugin/web-worker
// synaptic-backend-web-worker *
// synaptic-web-worker
// web-worker
requireByKind( 'plugin', 'backend-web-worker' )
// Would require this possibilities
// ./plugin/backend-web-worker
// synaptic-backend-backend-web-worker
// synaptic-backend-web-worker *
// backend-web-worker
requireByKind( 'plugin', 'synaptic-backend-web-worker' )
// Would require this possibilities
// ./plugin/synaptic-backend-web-worker
// synaptic-backend-synaptic-backend-web-worker
// synaptic-synaptic-backend-web-worker
// synaptic-backend-web-worker *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment