Skip to content

Commit b672452

Browse files
author
Luca Forstner
committed
fix(nextjs): Respect directives in value injection loader
1 parent ff8e780 commit b672452

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

packages/nextjs/src/config/loaders/valueInjectionLoader.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@ type LoaderOptions = {
44
values: Record<string, unknown>;
55
};
66

7+
// We need to be careful not to inject anything before any `"use strict";`s or "use client"s or really any other directive.
8+
// As an additional complication directives may come after any number of comments.
9+
// This regex is shamelessly stolen from: https://github.com/getsentry/sentry-javascript-bundler-plugins/blob/7f984482c73e4284e8b12a08dfedf23b5a82f0af/packages/bundler-plugin-core/src/index.ts#L535-L539
10+
const SKIP_COMMENT_AND_DIRECTIVE_REGEX =
11+
// Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.
12+
// Rollup doesn't like if we put this regex as a literal (?). No idea why.
13+
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor
14+
new RegExp('^(?:\\s*|/\\*(?:.|\\r|\\n)*?\\*/|//.*[\\n\\r])*(?:"[^"]*";|\'[^\']*\';)?');
15+
716
/**
817
* Set values on the global/window object at the start of a module.
918
*
@@ -22,5 +31,7 @@ export default function valueInjectionLoader(this: LoaderThis<LoaderOptions>, us
2231
.map(([key, value]) => `globalThis["${key}"] = ${JSON.stringify(value)};`)
2332
.join('\n');
2433

25-
return `${injectedCode}\n${userCode}`;
34+
return userCode.replace(SKIP_COMMENT_AND_DIRECTIVE_REGEX, match => {
35+
return match + injectedCode;
36+
});
2637
}

0 commit comments

Comments
 (0)