Skip to content

Commit

Permalink
Fix sorting of side-effect imports in Node <12
Browse files Browse the repository at this point in the history
`Array.prototype.sort` in Node <12 does not use stable sorting, and this
plugin accidentally relied on stable sorting to keep the original order
of side-effect imports. This commit makes sure that side effect imports
end up in their original order regardless of whether `.sort` is stable
or not.

Fixes #34 and closes #36.
  • Loading branch information
lydell committed Jan 24, 2020
1 parent 034254b commit 7343fc7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ easier to work with.

## Development

You can need [Node.js] 10 and npm 6.
You need [Node.js] ~12 and npm 6.

### npm scripts

Expand Down
2 changes: 1 addition & 1 deletion src/sort.js
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,7 @@ function sortImportItems(items) {
return items.slice().sort((itemA, itemB) =>
// If both items are side effect imports, keep their original order.
itemA.isSideEffectImport && itemB.isSideEffectImport
? 0
? itemA.index - itemB.index
: // If one of the items is a side effect import, move it first.
itemA.isSideEffectImport
? -1
Expand Down
15 changes: 15 additions & 0 deletions test/sort.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ const baseTests = expect => ({
|import "a"
`,

// Side-effect only imports use a stable sort (issure #34).
input`
|import "codemirror/addon/fold/brace-fold"
|import "codemirror/addon/edit/closebrackets"
|import "codemirror/addon/fold/foldgutter"
|import "codemirror/addon/fold/foldgutter.css"
|import "codemirror/addon/lint/json-lint"
|import "codemirror/addon/lint/lint"
|import "codemirror/addon/lint/lint.css"
|import "codemirror/addon/scroll/simplescrollbars"
|import "codemirror/addon/scroll/simplescrollbars.css"
|import "codemirror/lib/codemirror.css"
|import "codemirror/mode/javascript/javascript"
`,

// Sorted alphabetically.
input`
|import x1 from "a";
Expand Down

0 comments on commit 7343fc7

Please sign in to comment.