Created
July 15, 2012 07:01
-
-
Save devinrhode2/3115640 to your computer and use it in GitHub Desktop.
have require('file.js') fallback to trying require(./file.js')
This file contains 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
/* | |
let's say you have some js file in your root. It's natural to expect this to work: | |
require('thing.js'); | |
but it fails, reporting the module isn't available. | |
...but if it fails, why not check if it's at the root of the directory? | |
The below code overrides and wraps node's require function to do just that. | |
*/ | |
var normalRequire = require; | |
var require = function newRequire(module) { | |
var returnValue; | |
try { | |
returnValue = normalRequire(module); | |
} catch (e) { | |
var message = e.message.toString(); | |
//EcmaScript 6 .contains: | |
String.prototype.contains = function StringPrototypeContains(substring) { | |
return this.indexOf(substring) > -1; | |
}; | |
if (message.contains('Cannot find module')) { | |
var path = './' + message.substring(message.indexOf("'") + 1, message.length - 1); | |
console.log('going to do require(\'' + path + '\');'); | |
returnValue = require(path); | |
} | |
} | |
return returnValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a lot easier to just say
module.paths.push(__dirname)
. https://gist.github.com/3117649Note: This should not be done. It's a design goal to make local requires obviously different from "outside the package" requires (either builtin modules or package deps.)