Skip to content

Commit 05f8df0

Browse files
authored
Improve JS comment handling (#727)
1 parent 7e3b93d commit 05f8df0

File tree

1 file changed

+34
-1
lines changed
  • packages/tailwindcss-language-service/src/util

1 file changed

+34
-1
lines changed

packages/tailwindcss-language-service/src/util/doc.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { TextDocument, Range } from 'vscode-languageserver'
2+
import moo from 'moo'
23

34
export 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(
2728
function 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

Comments
 (0)