From beb5acea6bf8bddd21e27d41e02994c91c053836 Mon Sep 17 00:00:00 2001 From: Sebastian McKenzie Date: Fri, 2 Jan 2015 05:18:03 +1100 Subject: [PATCH] better addImport with good hoisting etc --- lib/6to5/file.js | 18 +++++++----------- .../transformation/transformers/es6-modules.js | 12 ++++++++++++ 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/lib/6to5/file.js b/lib/6to5/file.js index df1ba18e1d..a822d8eaa9 100644 --- a/lib/6to5/file.js +++ b/lib/6to5/file.js @@ -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"); diff --git a/lib/6to5/transformation/transformers/es6-modules.js b/lib/6to5/transformation/transformers/es6-modules.js index 64bcbff63b..b8c1b4964c 100644 --- a/lib/6to5/transformation/transformers/es6-modules.js +++ b/lib/6to5/transformation/transformers/es6-modules.js @@ -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; };