better addImport with good hoisting etc

This commit is contained in:
Sebastian McKenzie
2015-01-02 05:18:03 +11:00
parent 6a290f233e
commit beb5acea6b
2 changed files with 19 additions and 11 deletions

View File

@@ -10,11 +10,11 @@ var t = require("./types");
var _ = require("lodash");
function File(opts) {
this.unshiftProgramAtEnd = [];
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
this.dynamicImports = [];
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
}
File.declarations = [
@@ -157,7 +157,8 @@ File.prototype.parseShebang = function (code) {
File.prototype.addImport = function (id, source) {
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
this.unshiftProgramAtEnd.push(declar);
declar._blockHoist = 3;
this.dynamicImports.push(declar);
};
File.prototype.addDeclaration = function (name) {
@@ -231,11 +232,6 @@ File.prototype.transform = function (ast) {
_.each(this.transformers, function (transformer) {
transformer.transform(self);
var unshift = self.unshiftProgramAtEnd;
if (unshift.length) {
ast.program.body = unshift.concat(ast.program.body);
self.unshiftProgramAtEnd = [];
}
});
astRun("exit");

View File

@@ -1,5 +1,11 @@
var t = require("../../types");
exports.ast = {
before: function (ast, file) {
ast.program.body = file.dynamicImports.concat(ast.program.body);
}
};
exports.ImportDeclaration = function (node, parent, file) {
var nodes = [];
@@ -11,6 +17,12 @@ exports.ImportDeclaration = function (node, parent, file) {
file.moduleFormatter.importDeclaration(node, nodes, parent);
}
if (nodes.length === 1) {
// inherit `_blockHoist`
// this for `_blockHoist` in File.prototype.addImport
nodes[0]._blockHoist = node._blockHoist;
}
return nodes;
};