Last active
May 10, 2019 20:30
-
-
Save brendanmoore/0336e84444237ad1a8d41d3968f22cf4 to your computer and use it in GitHub Desktop.
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
/** | |
* 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