Add a transformer to import the runtime from a file

The `externalRuntime` optional transformer can be used in conjunction
with the `runtime` option to import and use the runtime from a module
instead of polluting the global environment.
This commit is contained in:
Aluísio Augusto Silva Gonçalves 2015-01-14 01:39:37 -02:00
parent 1c6cb7ce40
commit e8237910e8
4 changed files with 18 additions and 8 deletions

View File

@ -87,7 +87,7 @@ AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var key = t.getSpecifierName(specifier);
var ref = this._push(node);
if (t.isImportBatchSpecifier(specifier)) {
if (t.isImportBatchSpecifier(specifier) || node._noInteropRequire) {
// import * as bar from "foo";
} else if (t.isSpecifierDefault(specifier) && !this.noInteropRequire) {
// import foo from "foo";

View File

@ -26,13 +26,11 @@ CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes)
// import foo from "foo";
if (t.isSpecifierDefault(specifier)) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName,
t.callExpression(this.file.addHelper("interop-require"), [util.template("require", {
MODULE_NAME: node.source
})])
)
]));
var ref = util.template("require", {MODULE_NAME: node.source});
if (!node._noInteropRequire) {
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
}
nodes.push(t.variableDeclaration("var", [t.variableDeclarator(variableName, ref)]));
} else {
if (specifier.type === "ImportBatchSpecifier") {
// import * as bar from "foo";

View File

@ -95,6 +95,7 @@ _.each({
_moduleFormatter: require("./transformers/_module-formatter"),
typeofSymbol: require("./transformers/optional-typeof-symbol"),
externalRuntime: require("./transformers/optional-external-runtime"),
coreAliasing: require("./transformers/optional-core-aliasing"),
undefinedToVoid: require("./transformers/optional-undefined-to-void"),

View File

@ -0,0 +1,11 @@
exports.optional = true;
// In theory, it would be more appropriate to do this in `manipulateOptions`,
// but we need an identifier for the import and we can't get that before the
// AST is built.
exports.ast = {
enter: function (ast, file) {
file.opts.runtime = file.addImport(file.opts.runtime, "to5Runtime").name;
file.dynamicImports[file.dynamicImports.length - 1]._noInteropRequire = true;
}
};