forked from trivago/prettier-plugin-sort-imports
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: sort both script and scriptSetup, fix trivago#218
- Loading branch information
1 parent
a3b9893
commit 5ffeef5
Showing
1 changed file
with
29 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,39 @@ | ||
import type { SFCBlock, SFCDescriptor } from '@vue/compiler-sfc'; | ||
|
||
import { PrettierOptions } from '../types'; | ||
import { preprocessor } from './preprocessor'; | ||
|
||
export function vuePreprocessor(code: string, options: PrettierOptions) { | ||
const { parse } = require('@vue/compiler-sfc'); | ||
const { descriptor } = parse(code); | ||
const descriptor: SFCDescriptor = parse(code).descriptor; | ||
|
||
const content = (descriptor.script ?? descriptor.scriptSetup)?.content; | ||
if (!content) { | ||
// 1. filter valid blocks | ||
const blocks = [descriptor.script, descriptor.scriptSetup].filter( | ||
(block) => block?.content, | ||
) as SFCBlock[]; | ||
if (!blocks.length) { | ||
return code; | ||
} | ||
|
||
return code.replace(content, `\n${preprocessor(content, options)}\n`); | ||
// 2. sort blocks by start position | ||
blocks.sort((a, b) => a!.loc.start.offset - b!.loc.start.offset); | ||
|
||
// 3. replace blocks | ||
// Using offsets to avoid string replace catching the wrong place and improve efficiency | ||
let offset = 0; | ||
let result = ''; | ||
for (const block of blocks) { | ||
// https://github.com/vuejs/core/blob/9060bf0353e88cc1f4cf06981b9799c5c1e09466/packages/compiler-core/src/ast.ts#L71 | ||
// The node's range. The `start` is inclusive and `end` is exclusive. | ||
// [start, end) | ||
const { start, end } = block.loc; | ||
const trasnformed = `\n${preprocessor(block.content, options)}\n`; | ||
result += code.slice(offset, start.offset) + trasnformed; | ||
offset = end.offset; | ||
} | ||
|
||
// 4. append the rest | ||
result += code.slice(offset); | ||
|
||
return result; | ||
} |