Skip to content

Commit 31f1c52

Browse files
committed
switch from regex check to svelteCompiler.parse
1 parent e11dbfe commit 31f1c52

File tree

2 files changed

+6
-13
lines changed

2 files changed

+6
-13
lines changed

packages/svelte/rollup.npm.config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@ import { makeBaseNPMConfig, makeNPMConfigVariants } from '../../rollup/index.js'
33
export default makeNPMConfigVariants(
44
makeBaseNPMConfig({
55
// Prevent 'svelte/internal' stuff from being included in the built JS
6-
packageSpecificConfig: { external: ['svelte/internal'] },
6+
packageSpecificConfig: { external: ['svelte/internal', 'svelte/compiler'] },
77
}),
88
);

packages/svelte/src/preprocessors.ts

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import MagicString from 'magic-string';
2+
import * as svelteCompiler from 'svelte/compiler';
23
import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
34

45
import { ComponentTrackingInitOptions, SentryPreprocessorGroup, TrackComponentOptions } from './types';
@@ -123,16 +124,8 @@ function getBaseName(filename: string): string {
123124
}
124125

125126
function hasScriptTag(content: string): boolean {
126-
// This regex is taken from the Svelte compiler code.
127-
// They use this regex to find matching script tags that are passed to the `script` preprocessor hook:
128-
// https://github.com/sveltejs/svelte/blob/bb83eddfc623437528f24e9fe210885b446e72fa/src/compiler/preprocess/index.ts#L144
129-
// However, we remove the first part of the regex to not match HTML comments
130-
const scriptTagRegex = /<script(\s[^]*?)?(?:>([^]*?)<\/script>|\/>)/gi;
131-
132-
// Regex testing is not a super safe way of checking for the presence of a <script> tag in the Svelte
133-
// component file but I think we can use it as a start.
134-
// A case that is not covered by regex-testing HTML is e.g. nested <script> tags but I cannot
135-
// think of why one would do this in Svelte components. For instance, the Svelte compiler errors
136-
// when there's more than one top-level script tag.
137-
return scriptTagRegex.test(content);
127+
const ast = svelteCompiler.parse(content);
128+
// ast.instance holds whatever is defined in <script>
129+
// if there is no script tag, it's undefined.
130+
return ast.instance !== undefined;
138131
}

0 commit comments

Comments
 (0)