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 shorthand identifier import usage #9222

Merged
merged 8 commits into from
Sep 15, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/core/integration-tests/test/javascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
distDir,
outputFS,
inputFS,
fsFixture,
} from '@parcel/test-utils';
import {makeDeferredWithPromise, normalizePath} from '@parcel/utils';
import vm from 'vm';
Expand Down Expand Up @@ -6326,6 +6327,44 @@ describe('javascript', function () {
assert.equal(await res.default, 'target');
});

it('should detect shorthand identifier imports', async function () {
const dir = path.join(__dirname, 'js-import-shorthand-identifier');
overlayFS.mkdirp(dir);

await fsFixture(overlayFS, dir)`
package.json:
{
"name": "app",
"private": true,
"sideEffects": false
}

index.js:
import { tokens, mode } from "./tokens.js";

export default tokens;

tokens.js:
import { color } from "./color.js";

export const tokens = {
color,
};

export { mode } from "./color.js";

color.js:
export const color = "blue";
export const mode = "dark";`;

let b = await bundle(path.join(dir, '/index.js'), {
inputFS: overlayFS,
});

let output = await run(b);
assert.deepEqual(output.default, {color: 'blue'});
});

for (let shouldScopeHoist of [false, true]) {
let options = {
defaultTargetOptions: {
Expand Down
10 changes: 10 additions & 0 deletions packages/transformers/js/core/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,16 @@ impl Visit for Collect {
}
}

fn visit_ident(&mut self, node: &Ident) {
// This visitor helps us identify used imports in cases like:
//
// import { foo } from "bar";
// const baz = { foo };
if self.imports.contains_key(&id!(node)) {
Copy link
Contributor Author

@jondlm jondlm Aug 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't think of any cases where this new visitor would be problematic since SWC seems to imply that checking the id here helps us uniquely identify the correct use accounting for scope. Let me know if I'm wrong! I am very new to using Rust with SWC.

self.used_imports.insert(id!(node));
}
}

fn visit_this_expr(&mut self, node: &ThisExpr) {
if self.in_module_this {
self.has_cjs_exports = true;
Expand Down