Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix assigning to exports from inside a function in scope hoisting #2994

Merged
merged 3 commits into from May 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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