From 81cb88cfc1ee4239378603e1f56228cd137ed9ed Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Tue, 22 Nov 2016 09:30:54 -0500 Subject: [PATCH] hoist imports --- compiler/generate/index.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/compiler/generate/index.js b/compiler/generate/index.js index 6e4a362230..75ad1b87fe 100644 --- a/compiler/generate/index.js +++ b/compiler/generate/index.js @@ -104,10 +104,25 @@ export default function generate ( parsed, source, options = {} ) { }; const templateProperties = {}; + const imports = []; if ( parsed.js ) { generator.addSourcemapLocations( parsed.js.content ); + // imports need to be hoisted out of the IIFE + for ( let i = 0; i < parsed.js.content.body.length; i += 1 ) { + const node = parsed.js.content.body[i]; + if ( node.type === 'ImportDeclaration' ) { + let a = node.start; + let b = node.end; + while ( /[ \t]/.test( source[ a - 1 ] ) ) a -= 1; + while ( source[b] === '\n' ) b += 1; + + imports.push( source.slice( a, b ).replace( /^\s/, '' ) ); + generator.code.remove( a, b ); + } + } + const defaultExport = parsed.js.content.body.find( node => node.type === 'ExportDefaultDeclaration' ); if ( defaultExport ) { @@ -234,6 +249,10 @@ export default function generate ( parsed, source, options = {} ) { const topLevelStatements = []; if ( parsed.js ) { + if ( imports.length ) { + topLevelStatements.push( imports.join( '' ).trim() ); + } + topLevelStatements.push( `[✂${parsed.js.content.start}-${parsed.js.content.end}✂]` ); }