Skip to content

Commit 81cb88c

Browse files
committed
hoist imports
1 parent 4685c1e commit 81cb88c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

compiler/generate/index.js

+19
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,25 @@ export default function generate ( parsed, source, options = {} ) {
104104
};
105105

106106
const templateProperties = {};
107+
const imports = [];
107108

108109
if ( parsed.js ) {
109110
generator.addSourcemapLocations( parsed.js.content );
110111

112+
// imports need to be hoisted out of the IIFE
113+
for ( let i = 0; i < parsed.js.content.body.length; i += 1 ) {
114+
const node = parsed.js.content.body[i];
115+
if ( node.type === 'ImportDeclaration' ) {
116+
let a = node.start;
117+
let b = node.end;
118+
while ( /[ \t]/.test( source[ a - 1 ] ) ) a -= 1;
119+
while ( source[b] === '\n' ) b += 1;
120+
121+
imports.push( source.slice( a, b ).replace( /^\s/, '' ) );
122+
generator.code.remove( a, b );
123+
}
124+
}
125+
111126
const defaultExport = parsed.js.content.body.find( node => node.type === 'ExportDefaultDeclaration' );
112127

113128
if ( defaultExport ) {
@@ -234,6 +249,10 @@ export default function generate ( parsed, source, options = {} ) {
234249
const topLevelStatements = [];
235250

236251
if ( parsed.js ) {
252+
if ( imports.length ) {
253+
topLevelStatements.push( imports.join( '' ).trim() );
254+
}
255+
237256
topLevelStatements.push( `[✂${parsed.js.content.start}-${parsed.js.content.end}✂]` );
238257
}
239258

0 commit comments

Comments
 (0)