Skip to content

Instantly share code, notes, and snippets.

@themouette
Created June 29, 2015 22:56
Show Gist options
  • Save themouette/643ea905ce71ea98725b to your computer and use it in GitHub Desktop.
Save themouette/643ea905ce71ea98725b to your computer and use it in GitHub Desktop.
babel hook to load modules from several directories
/**
* 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;
};
const lookupDirs = ['app/server', 'app/shared/lib', 'app/shared'];
const resolveModuleSource = require('./babel-hooks');
require('babel/register')({
stage: 1,
resolveModuleSource: resolveModuleSource(lookupDirs)
});
require('./app');
@themouette
Copy link
Author

All files in lookupDirs can be imported just as if they were at the repository root:

For instance to import app/server/foo.js

import foo from 'foo';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment