Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brendanmoore/0336e84444237ad1a8d41d3968f22cf4 to your computer and use it in GitHub Desktop.
Save brendanmoore/0336e84444237ad1a8d41d3968f22cf4 to your computer and use it in GitHub Desktop.
/**
* Please note this code is just a proof of concept and should not
* be used in production!
*
* Based on https://github.com/airbnb/babel-plugin-dynamic-import-node
*/
import syntax from 'babel-plugin-syntax-dynamic-import';
export default function ({ template, types: t }) {
// Uses a hacky "thennable" return object that invokes the callbacks synchronusly,
// Will not work if the import function does follow up `.then/.catch`
//
// i.e.
// import().then(...) // <-- Should be fine
// import().then(...).then(...) // <-- Nope
const buildImport = template(` (function(modulePath) {
var e;
try {
var m = require(modulePath);
} catch (err) {
e = err;
}
return {
then: function(cb, errCb) {
if (e && errCb) {
errCb(e);
} else {
cb(m);
}
},
catch: function(cb) {
if (e) {
cb(e);
}
}
};
})(SOURCE);`);
return {
inherits: syntax,
visitor: {
Import(path) {
const importArguments = path.parentPath.node.arguments;
const isString = t.isStringLiteral(importArguments[0])
|| t.isTemplateLiteral(importArguments[0]);
if (isString) {
t.removeComments(importArguments[0]);
}
const newImport = buildImport({
SOURCE: (isString)
? importArguments
: t.templateLiteral([
t.templateElement({ raw: '', cooked: '' }),
t.templateElement({ raw: '', cooked: '' }, true),
], importArguments),
});
path.parentPath.replaceWith(newImport);
},
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment