Skip to content

Commit

Permalink
Fix assigning to exports from inside a function in scope hoisting (#2994
Browse files Browse the repository at this point in the history
)
  • Loading branch information
devongovett committed May 9, 2019
1 parent 84b3085 commit 7ddb838
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 6 deletions.
@@ -0,0 +1,4 @@
var b = require('./b');

b.setValue(2);
module.exports = b.value;
@@ -0,0 +1,3 @@
exports.setValue = function (value) {
exports.value = value;
}
12 changes: 12 additions & 0 deletions packages/core/integration-tests/test/scope-hoisting.js
Expand Up @@ -1217,5 +1217,17 @@ describe('scope hoisting', function() {
assert.equal(output.__esModule, true);
assert.equal(output.default, 2);
});

it('should support assigning to exports from inside a function', async function() {
let b = await bundle(
path.join(
__dirname,
'/integration/scope-hoisting/commonjs/export-assign-scope/a.js'
)
);

let output = await run(b);
assert.deepEqual(output, 2);
});
});
});
22 changes: 16 additions & 6 deletions packages/core/parcel-bundler/src/scope-hoisting/hoist.js
Expand Up @@ -268,13 +268,23 @@ module.exports = {
let scope = path.scope.getProgramParent();
if (!scope.hasBinding(identifier.name)) {
asset.cacheData.exports[name] = identifier.name;
let [decl] = path.insertBefore(
t.variableDeclaration('var', [
t.variableDeclarator(t.clone(identifier), right)
])
);

scope.registerDeclaration(decl);
// If in the program scope, create a variable declaration and initialize with the exported value.
// Otherwise, declare the variable in the program scope, and assign to it here.
if (path.scope === scope) {
let [decl] = path.insertBefore(
t.variableDeclaration('var', [
t.variableDeclarator(t.clone(identifier), right)
])
);

scope.registerDeclaration(decl);
} else {
scope.push({id: t.clone(identifier)});
path.insertBefore(
t.assignmentExpression('=', t.clone(identifier), right)
);
}
} else {
path.insertBefore(
t.assignmentExpression('=', t.clone(identifier), right)
Expand Down

0 comments on commit 7ddb838

Please sign in to comment.