better dynamic imports - fixes #393

This commit is contained in:
Sebastian McKenzie
2015-01-05 12:40:12 +11:00
parent 5ce8ee6c2b
commit 348ad2e25c
3 changed files with 23 additions and 16 deletions

View File

@@ -10,11 +10,12 @@ var t = require("./types");
var _ = require("lodash");
function File(opts) {
this.dynamicImports = [];
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
this.dynamicImports = [];
this.dynamicImportIds = {};
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
}
File.helpers = [
@@ -164,11 +165,20 @@ File.prototype.parseShebang = function (code) {
return code;
};
File.prototype.addImport = function (id, source) {
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImports.push(declar);
File.prototype.addImport = function (source, name) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
id = this.dynamicImportIds[name] = this.generateUidIdentifier(name);
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImports.push(declar);
}
return id;
};
File.prototype.addHelper = function (name) {
@@ -277,7 +287,7 @@ File.prototype.generate = function () {
};
File.prototype.generateUid = function (name, scope) {
name = t.toIdentifier(name);
name = t.toIdentifier(name).replace(/^_+/, "");
scope = scope || this.scope;

View File

@@ -38,8 +38,6 @@ exports._Function = function (node, callId) {
exports.Function = function (node, parent, file) {
if (!node.async || node.generator) return;
var id = t.identifier("Bluebird");
file.addImport(id, "bluebird");
var id = file.addImport("bluebird");
return exports._Function(node, t.memberExpression(id, t.identifier("coroutine")));
};

View File

@@ -12,8 +12,7 @@ exports.optional = true;
exports.ast = {
enter: function (ast, file) {
file._coreId = file.generateUidIdentifier("core");
file.addImport(file._coreId, "core-js/library");
file._coreId = file.addImport("core-js/library", "core");
},
exit: function (ast, file) {