forked from sveltejs/eslint-plugin-svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabel.ts
60 lines (56 loc) · 1.32 KB
/
babel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import type { AST } from 'svelte-eslint-parser';
import type babelCore from '@babel/core';
import type { RuleContext } from '../../../types.js';
import type { TransformResult } from './types.js';
import { loadModule } from '../../../utils/load-module.js';
type BabelCore = typeof babelCore;
/**
* Transpile with babel
*/
export function transform(
node: AST.SvelteScriptElement,
text: string,
context: RuleContext
): TransformResult | null {
const babel = loadBabel(context);
if (!babel) {
return null;
}
let inputRange: AST.Range;
if (node.endTag) {
inputRange = [node.startTag.range[1], node.endTag.range[0]];
} else {
inputRange = [node.startTag.range[1], node.range[1]];
}
const code = text.slice(...inputRange);
try {
const output = babel.transformSync(code, {
sourceType: 'module',
sourceMaps: true,
minified: false,
ast: false,
code: true,
cwd: context.cwd ?? process.cwd()
});
if (!output) {
return null;
}
return {
inputRange,
output: output.code!,
mappings: output.map!.mappings
};
} catch {
return null;
}
}
/** Check if project has Babel. */
export function hasBabel(context: RuleContext): boolean {
return Boolean(loadBabel(context));
}
/**
* Load babel
*/
function loadBabel(context: RuleContext): BabelCore | null {
return loadModule(context, '@babel/core');
}