Skip to content

Commit 0f3a062

Browse files
authored
Fix: Vue preprocessor: Support variations in block syntax (#247)
Fixes #246 Change to handle both `block.loc.start` and `block.start` also during the initial sorting. In the rest of the file this is already handled by #173
1 parent 89894c1 commit 0f3a062

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

src/preprocessors/vue.ts

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ import { PrettierOptions } from '../types';
55
import { hasPlugin } from '../utils/get-experimental-parser-plugins';
66
import { preprocessor } from './preprocessor';
77

8+
// Non-exhaustive, describes just the properties needed for type guarding
9+
type BaseBlock = { start: { offset: number }; end: { offset: number } };
10+
type LocBlock = { loc: BaseBlock };
11+
type VueBlock = BaseBlock | LocBlock;
12+
813
export function vuePreprocessor(code: string, options: PrettierOptions) {
914
try {
1015
const { parse } = require('@vue/compiler-sfc');
@@ -23,7 +28,11 @@ export function vuePreprocessor(code: string, options: PrettierOptions) {
2328
}
2429

2530
// 2. Sort blocks by start offset.
26-
blocks.sort((a, b) => a.loc.start.offset - b.loc.start.offset);
31+
blocks.sort((a: VueBlock, b: VueBlock) => {
32+
const startA = isLocBlock(a) ? a.loc.start : a.start;
33+
const startB = isLocBlock(b) ? b.loc.start : b.start;
34+
return startA.offset - startB.offset;
35+
});
2736

2837
// 3. Replace blocks.
2938
// Using offsets to avoid string replace catching the wrong place and improve efficiency
@@ -35,12 +44,12 @@ export function vuePreprocessor(code: string, options: PrettierOptions) {
3544
// The node's range. The `start` is inclusive and `end` is exclusive.
3645
// [start, end)
3746

38-
// @ts-expect-error Some vue versions have a `block.loc`, others have start and end directly on the block
39-
let { start, end } = block;
40-
if ('loc' in block) {
41-
start = block.loc.start.offset;
42-
end = block.loc.end.offset;
43-
}
47+
const start = isLocBlock(block)
48+
? block.loc.start.offset
49+
: (block as BaseBlock).start.offset;
50+
const end = isLocBlock(block)
51+
? block.loc.end.offset
52+
: (block as BaseBlock).end.offset;
4453
const preprocessedBlockCode = sortScript(block, options);
4554
result += code.slice(offset, start) + preprocessedBlockCode;
4655
offset = end;
@@ -59,6 +68,13 @@ export function vuePreprocessor(code: string, options: PrettierOptions) {
5968
}
6069
}
6170

71+
/**
72+
* Some Vue versions have the start/end offsets under a `block.loc`, others have them directly on the block
73+
*/
74+
function isLocBlock(b: VueBlock): b is LocBlock {
75+
return 'loc' in b;
76+
}
77+
6278
function isTS(lang?: string) {
6379
return lang === 'ts' || lang === 'tsx';
6480
}

0 commit comments

Comments
 (0)