1
- import _generate from '@babel/generator'
2
- import { parse } from '@babel/parser'
3
- import _traverse from '@babel/traverse'
4
-
5
- import type { Node , StringLiteral , TemplateElement } from '@babel/types'
6
- import type { TraverseOptions , IHandlerOptions } from '../types'
1
+ import type { StringLiteral , TemplateElement } from '@babel/types'
2
+ import { transformSync , type BabelFileResult , type NodePath } from '@babel/core'
3
+ import type { IHandlerOptions } from '../types'
7
4
import { escapeStringRegexp } from '../utils'
8
5
import { splitCode } from './split'
9
6
10
- function getDefaultExportFromNamespaceIfPresent ( n : any ) {
11
- return n && Object . prototype . hasOwnProperty . call ( n , 'default' ) ? n . default : n
12
- }
13
- const generate = getDefaultExportFromNamespaceIfPresent ( _generate ) as typeof _generate
14
- const traverse = getDefaultExportFromNamespaceIfPresent ( _traverse ) as typeof _traverse
15
-
16
7
export function makeRegex ( str : string ) {
17
8
return new RegExp ( '(?<=^|[\\s"])' + escapeStringRegexp ( str ) , 'g' )
18
9
}
@@ -39,25 +30,33 @@ export function handleValue(str: string, node: StringLiteral | TemplateElement,
39
30
}
40
31
41
32
export function jsHandler ( rawSource : string , options : IHandlerOptions ) {
42
- const ast = parse ( rawSource )
43
-
44
- const topt : TraverseOptions < Node > = {
45
- StringLiteral : {
46
- enter ( p ) {
47
- const n = p . node
48
- n . value = handleValue ( n . value , n , options )
33
+ const result = transformSync ( rawSource , {
34
+ babelrc : false ,
35
+ ast : true ,
36
+ plugins : [
37
+ ( ) => {
38
+ return {
39
+ visitor : {
40
+ StringLiteral : {
41
+ enter ( p : NodePath < StringLiteral > ) {
42
+ const n = p . node
43
+ n . value = handleValue ( n . value , n , options )
44
+ }
45
+ } ,
46
+ TemplateElement : {
47
+ enter ( p : NodePath < TemplateElement > ) {
48
+ const n = p . node
49
+ n . value . raw = handleValue ( n . value . raw , n , options )
50
+ }
51
+ }
52
+ // noScope: true
53
+ }
54
+ }
49
55
}
50
- } ,
51
- TemplateElement : {
52
- enter ( p ) {
53
- const n = p . node
54
- n . value . raw = handleValue ( n . value . raw , n , options )
55
- }
56
- } ,
57
- noScope : true
58
- }
59
-
60
- traverse ( ast , topt )
56
+ ] ,
57
+ sourceMaps : false ,
58
+ configFile : false
59
+ } )
61
60
62
- return generate ( ast )
61
+ return result as BabelFileResult
63
62
}
0 commit comments