1
1
import type { TextDocument , Range } from 'vscode-languageserver'
2
+ import moo from 'moo'
2
3
3
4
export function getTextWithoutComments (
4
5
doc : TextDocument ,
@@ -14,7 +15,7 @@ export function getTextWithoutComments(
14
15
let text = typeof docOrText === 'string' ? docOrText : docOrText . getText ( range )
15
16
16
17
if ( type === 'js' || type === 'jsx' ) {
17
- return text . replace ( / \/ \* . * ? \* \/ / gs , replace ) . replace ( / \/ \/ . * ? $ / gms , replace )
18
+ return getJsWithoutComments ( text )
18
19
}
19
20
20
21
if ( type === 'css' ) {
@@ -27,3 +28,35 @@ export function getTextWithoutComments(
27
28
function replace ( match : string ) : string {
28
29
return match . replace ( / ./ gs, ( char ) => ( char === '\n' ? '\n' : ' ' ) )
29
30
}
31
+
32
+ let jsLexer : moo . Lexer
33
+
34
+ function getJsWithoutComments ( text : string ) : string {
35
+ if ( ! jsLexer ) {
36
+ jsLexer = moo . states ( {
37
+ main : {
38
+ commentLine : / \/ \/ .* ?$ / ,
39
+ commentBlock : { match : / \/ \* [ ^ ] * ?\* \/ / , lineBreaks : true } ,
40
+ stringDouble : / " (?: [ ^ " \\ ] | \\ .) * " / ,
41
+ stringSingle : / ' (?: [ ^ ' \\ ] | \\ .) * ' / ,
42
+ stringBacktick : / ` (?: [ ^ ` \\ ] | \\ .) * ` / ,
43
+ other : { match : / [ ^ ] / , lineBreaks : true } ,
44
+ } ,
45
+ } )
46
+ }
47
+
48
+ let str = ''
49
+ jsLexer . reset ( text )
50
+
51
+ for ( let token of jsLexer ) {
52
+ if ( token . type === 'commentLine' ) {
53
+ str += ' ' . repeat ( token . value . length )
54
+ } else if ( token . type === 'commentBlock' ) {
55
+ str += token . value . replace ( / ./ g, ' ' )
56
+ } else {
57
+ str += token . value
58
+ }
59
+ }
60
+
61
+ return str
62
+ }
0 commit comments