/** * 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); }, }, }; }