11import type { TextDocument , Range } from 'vscode-languageserver'
2+ import moo from 'moo'
23
34export function getTextWithoutComments (
45 doc : TextDocument ,
@@ -14,7 +15,7 @@ export function getTextWithoutComments(
1415 let text = typeof docOrText === 'string' ? docOrText : docOrText . getText ( range )
1516
1617 if ( type === 'js' || type === 'jsx' ) {
17- return text . replace ( / \/ \* . * ? \* \/ / gs , replace ) . replace ( / \/ \/ . * ? $ / gms , replace )
18+ return getJsWithoutComments ( text )
1819 }
1920
2021 if ( type === 'css' ) {
@@ -27,3 +28,35 @@ export function getTextWithoutComments(
2728function replace ( match : string ) : string {
2829 return match . replace ( / ./ gs, ( char ) => ( char === '\n' ? '\n' : ' ' ) )
2930}
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