Created
November 14, 2016 15:09
-
-
Save cusspvz/f77f5a0e3fb201c9816f33cad6274cfd to your computer and use it in GitHub Desktop.
require-by-kind
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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