Created
June 29, 2015 22:56
-
-
Save themouette/643ea905ce71ea98725b to your computer and use it in GitHub Desktop.
babel hook to load modules from several directories
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
/** | |
* Hook babel compilation into require. | |
* | |
* To disable cache, see https://babeljs.io/docs/usage/require/#environment-variables | |
* | |
* ``` javascript | |
* const lookupDirs = ['app/server', 'app/shared/lib', 'app/shared']; | |
* const resolveModuleSource = require('babel-hooks'); | |
* | |
* require('babel/register')({ | |
* stage: 1, | |
* resolveModuleSource: resolveModuleSource(lookupDirs) | |
* }); | |
* ``` | |
*/ | |
const fs = require('fs'); | |
const path = require('path'); | |
const extensions = ['js', 'jsx', 'json']; | |
module.exports = function resolveModuleSource(_lookupDirs) { | |
var lookupDirs = _lookupDirs.map(function makeAbsolute(x) { | |
return path.join(__dirname, x); | |
}); | |
function resolveExtension(absolutePath) { | |
var currTest; | |
for (var i = 0; i < extensions.length; i++) { | |
currTest = [absolutePath, extensions[i]].join('.'); | |
if (fs.existsSync(currTest)) { | |
return currTest; | |
} | |
} | |
} | |
function resolveFilename(source/*, filename*/) { | |
var file; | |
if (source[0] === '.') { | |
return source; | |
} | |
// this is an absolute path | |
for (var i = 0; i < lookupDirs.length; i++) { | |
file = path.join(lookupDirs[i], source); | |
file = resolveExtension(file); | |
if (file) { | |
return file; | |
} | |
} | |
// none of the special path matched | |
return source; | |
} | |
return resolveFilename; | |
}; |
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
const lookupDirs = ['app/server', 'app/shared/lib', 'app/shared']; | |
const resolveModuleSource = require('./babel-hooks'); | |
require('babel/register')({ | |
stage: 1, | |
resolveModuleSource: resolveModuleSource(lookupDirs) | |
}); | |
require('./app'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All files in
lookupDirs
can be imported just as if they were at the repository root:For instance to import
app/server/foo.js