Skip to content

[Bug] merge_imports compression reorders imports incorrectly and places them after usage #11257

@Timeless0911

Description

@Timeless0911

Describe the bug

When enabling the merge_imports option in SWC's compression transform, imports are being reordered incorrectly and placed after their usage in the code. This breaks the expected execution order and make output not aesthetically pleasing.

Input code

import { v1 } from 'a';
import { v2 } from 'b';
import { v3 } from 'b';
import { v4 } from 'c';

console.log(v1, v2, v3, v4);

Link to the code that reproduces this issue

https://play.swc.rs/?version=1.15.1&code=H4sIAAAAAAAAA8vMLcgvKlGoVigzVKhVSCvKz1VQT1S35sqEixvBxZNQxI1xiJvAxZOB4lzJ%2BXnF%2BTmpejn56RplhjpA84DYGIhNNK0Bz34%2BxH0AAAA%3D&config=H4sIAAAAAAAAA32VO4%2FbMAyA9%2F6KwHMLHFKgQ%2BeiW9eugiJRjq62ZJBULsYh%2F72UH7lcQmeL%2BfEhPvP%2BZbdrXsk1P3fv8lM%2BBosEeP0WCY2J7VkkDY8DkMM4cPN1pUwVBdsRXGUeXEbLGUkQY4EJXGbesMUWuPoD2r%2Fs980qR5soZOxvg3fQWjf%2BWh1uh%2FoLSDGn6rY6%2FfbyvfkUtY8phvHWtcv9gEB0IxOpPK70kJjuQ00M89ua0438kHMH8vhtYiyZmBhaQM2xy11nBwJzsqh4qS%2B1GClrISosDN4MmAeVJx9ZSiMxH6kH643LHhQUERzHE2hmEkvMEkl6Sj4T9nAobTvN0p01nGxXLCsx4Ty1ZG7kvddjjsQmlKSVcIYbNZjhUtx7yxgMAhdMj3avOaaNnvwDkAp0lijZHjS%2Fk0aQedqyDk8tYwoysjwqvMtqlkl2hcHEGJTK1soActS6ieCLg1pZpz1nwRvlo%2BjBQAgyK4preovsjlrQekxyUID01wZtqmZgrlu4wetCPMG%2FJUvWB2zR6C0ftymN%2FSF3TwL0wMfsnyhIKzhvY5QrcR62eUkeZDTAqyqFJvB4BGQBOJtuurwPsyHrIR5N2%2BXDx5lYFC7XY9vb1H7s%2B6fzKiNJCmn67Mtksvy91K7Pp%2F9Hvc%2BL0nqbr%2Bk0kf6slvNjL%2F8BoiZ%2BXKsGAAA%3D

SWC Info output

No response

Expected behavior

import { v1 } from 'a';
import { v2, v3 } from 'b';
import { v4 } from 'c';

console.log(v1, v2, v3, v4);

Actual behavior

import { v1 } from 'a';
import { v4 } from 'c';
console.log(v1, v2, v3, v4);
import { v2, v3 } from "b";

Version

latest

Additional context

Problem Analysis

  • Semantic Breaking: The transformation changes the semantics of the program by altering the execution order. The import from module 'b' is placed after imports from 'a' and 'c', which changes the original import order.
  • Imports After Usage: The merged import import { v2, v3 } from "b" is placed after the console.log statement where these variables are used. This is not aesthetically pleasing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions