Skip to content

Commit 152b618

Browse files
committed
add vite plugin for react router
1 parent a31e0d3 commit 152b618

File tree

10 files changed

+756
-3
lines changed

10 files changed

+756
-3
lines changed

packages/react-router/package.json

+4-2
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,13 @@
3636
"dependencies": {
3737
"@sentry/browser": "9.0.1",
3838
"@sentry/core": "9.0.1",
39-
"@sentry/node": "9.0.1"
39+
"@sentry/node": "9.0.1",
40+
"@sentry/vite-plugin": "^3.1.2"
4041
},
4142
"devDependencies": {
4243
"@react-router/node": "^7.1.5",
43-
"react-router": "^7.1.5"
44+
"react-router": "^7.1.5",
45+
"vite": "^6.1.0"
4446
},
4547
"peerDependencies": {
4648
"@react-router/node": "7.x",

packages/react-router/src/index.types.ts

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
export * from './client';
44
export * from './server';
5+
export * from './vite';
56

67
import type { Integration, Options, StackParser } from '@sentry/core';
78
import type * as clientSdk from './client';
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { sentryReactRouter } from './plugin';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { consoleSandbox } from '@sentry/core';
2+
import { sentryVitePlugin } from '@sentry/vite-plugin';
3+
import type { Plugin, UserConfig } from 'vite';
4+
import type { SentryReactRouterPluginOptions } from './types';
5+
6+
/**
7+
* Creates sentry's vite plugins
8+
*/
9+
export function makeSentryVitePlugins(options: SentryReactRouterPluginOptions, viteConfig: UserConfig): Plugin[] {
10+
const {
11+
debug,
12+
sourceMapsUploadOptions,
13+
unstable_sentryVitePluginOptions,
14+
bundleSizeOptimizations,
15+
authToken,
16+
org,
17+
project,
18+
} = options;
19+
20+
let updatedFilesToDeleteAfterUpload: string[] | undefined = undefined;
21+
22+
if (
23+
typeof sourceMapsUploadOptions?.filesToDeleteAfterUpload === 'undefined' &&
24+
typeof unstable_sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload === 'undefined' &&
25+
// Only if source maps were previously not set, we update the "filesToDeleteAfterUpload" (as we override the setting with "hidden")
26+
typeof viteConfig.build?.sourcemap === 'undefined'
27+
) {
28+
// For .output, .vercel, .netlify etc.
29+
updatedFilesToDeleteAfterUpload = ['.*/**/*.map'];
30+
31+
consoleSandbox(() => {
32+
// eslint-disable-next-line no-console
33+
console.log(
34+
`[Sentry] Automatically setting \`sourceMapsUploadOptions.filesToDeleteAfterUpload: ${JSON.stringify(
35+
updatedFilesToDeleteAfterUpload,
36+
)}\` to delete generated source maps after they were uploaded to Sentry.`,
37+
);
38+
});
39+
}
40+
41+
return [
42+
...sentryVitePlugin({
43+
authToken: authToken ?? process.env.SENTRY_AUTH_TOKEN,
44+
bundleSizeOptimizations,
45+
debug: debug ?? false,
46+
org: org ?? process.env.SENTRY_ORG,
47+
project: project ?? process.env.SENTRY_PROJECT,
48+
sourcemaps: {
49+
filesToDeleteAfterUpload:
50+
(sourceMapsUploadOptions?.filesToDeleteAfterUpload ||
51+
unstable_sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload) ??
52+
updatedFilesToDeleteAfterUpload,
53+
...unstable_sentryVitePluginOptions?.sourcemaps,
54+
},
55+
telemetry: sourceMapsUploadOptions?.telemetry ?? true,
56+
_metaOptions: {
57+
telemetry: {
58+
metaFramework: 'react-router',
59+
},
60+
},
61+
...unstable_sentryVitePluginOptions,
62+
}),
63+
];
64+
}
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import type { Plugin, UserConfig } from 'vite';
2+
import { makeSentryVitePlugins } from './makeSentryVitePlugin';
3+
import { makeEnableSourceMapsVitePlugins } from './sourceMaps';
4+
import type { SentryReactRouterPluginOptions } from './types';
5+
6+
/**
7+
* A Vite plugin for Sentry that handles source map uploads and bundle size optimizations.
8+
*
9+
* @param options - Configuration options for the Sentry Vite plugin
10+
* @param viteConfig - The Vite user config object
11+
* @returns An array of Vite plugins
12+
*/
13+
export function sentryReactRouter(options: SentryReactRouterPluginOptions = {}, viteConfig: UserConfig): Plugin[] {
14+
const plugins: Plugin[] = [];
15+
16+
if (process.env.NODE_ENV !== 'development') {
17+
if (options.sourceMapsUploadOptions?.enabled ?? true) {
18+
plugins.push(...makeSentryVitePlugins(options, viteConfig));
19+
plugins.push(...makeEnableSourceMapsVitePlugins(options));
20+
}
21+
}
22+
23+
return plugins;
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import type { Plugin, UserConfig } from 'vite';
2+
import type { SentryReactRouterPluginOptions } from './types';
3+
import { consoleSandbox } from '@sentry/core';
4+
5+
/**
6+
* A Sentry plugin for React Router to enable "hidden" source maps if they are unset.
7+
*/
8+
export function makeEnableSourceMapsVitePlugins(options: SentryReactRouterPluginOptions): Plugin[] {
9+
return [
10+
{
11+
name: 'sentry-react-router-update-source-map-setting',
12+
apply: 'build',
13+
enforce: 'post',
14+
config(viteConfig) {
15+
return {
16+
...viteConfig,
17+
build: {
18+
...viteConfig.build,
19+
sourcemap: getUpdatedSourceMapSettings(viteConfig, options),
20+
},
21+
};
22+
},
23+
},
24+
];
25+
}
26+
27+
/** There are 3 ways to set up source map generation
28+
*
29+
* 1. User explicitly disabled source maps
30+
* - keep this setting (emit a warning that errors won't be unminified in Sentry)
31+
* - we won't upload anything
32+
*
33+
* 2. Users enabled source map generation (true, 'hidden', 'inline').
34+
* - keep this setting (don't do anything - like deletion - besides uploading)
35+
*
36+
* 3. Users didn't set source maps generation
37+
* - we enable 'hidden' source maps generation
38+
* - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this)
39+
*
40+
* --> only exported for testing
41+
*/
42+
export function getUpdatedSourceMapSettings(
43+
viteConfig: UserConfig,
44+
sentryPluginOptions?: SentryReactRouterPluginOptions,
45+
): boolean | 'inline' | 'hidden' {
46+
viteConfig.build = viteConfig.build || {};
47+
48+
const viteSourceMap = viteConfig?.build?.sourcemap;
49+
let updatedSourceMapSetting = viteSourceMap;
50+
51+
const settingKey = 'vite.build.sourcemap';
52+
53+
if (viteSourceMap === false) {
54+
updatedSourceMapSetting = viteSourceMap;
55+
56+
consoleSandbox(() => {
57+
// eslint-disable-next-line no-console
58+
console.warn(
59+
`[Sentry] Source map generation is currently disabled in your Vite configuration (\`${settingKey}: false \`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`,
60+
);
61+
});
62+
} else if (viteSourceMap && ['hidden', 'inline', true].includes(viteSourceMap)) {
63+
updatedSourceMapSetting = viteSourceMap;
64+
65+
if (sentryPluginOptions?.debug) {
66+
consoleSandbox(() => {
67+
// eslint-disable-next-line no-console
68+
console.log(
69+
`[Sentry] We discovered \`${settingKey}\` is set to \`${viteSourceMap.toString()}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`,
70+
);
71+
});
72+
}
73+
} else {
74+
updatedSourceMapSetting = 'hidden';
75+
76+
consoleSandbox(() => {
77+
// eslint-disable-next-line no-console
78+
console.log(
79+
`[Sentry] Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`,
80+
);
81+
});
82+
}
83+
84+
return updatedSourceMapSetting;
85+
}
+126
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import type { SentryVitePluginOptions } from '@sentry/vite-plugin';
2+
3+
type SourceMapsOptions = {
4+
/**
5+
* If this flag is `true`, and an auth token is detected, the Sentry SDK will
6+
* automatically generate and upload source maps to Sentry during a production build.
7+
*
8+
* @default true
9+
*/
10+
enabled?: boolean;
11+
12+
/**
13+
* If this flag is `true`, the Sentry plugin will collect some telemetry data and send it to Sentry.
14+
* It will not collect any sensitive or user-specific data.
15+
*
16+
* @default true
17+
*/
18+
telemetry?: boolean;
19+
20+
/**
21+
* A glob or an array of globs that specifies the build artifacts that should be deleted after the artifact
22+
* upload to Sentry has been completed.
23+
*
24+
* @default [] - By default no files are deleted.
25+
*
26+
* The globbing patterns follow the implementation of the glob package. (https://www.npmjs.com/package/glob)
27+
*/
28+
filesToDeleteAfterUpload?: string | Array<string>;
29+
};
30+
31+
type BundleSizeOptimizationOptions = {
32+
/**
33+
* If set to `true`, the plugin will attempt to tree-shake (remove) any debugging code within the Sentry SDK.
34+
* Note that the success of this depends on tree shaking being enabled in your build tooling.
35+
*
36+
* Setting this option to `true` will disable features like the SDK's `debug` option.
37+
*/
38+
excludeDebugStatements?: boolean;
39+
40+
/**
41+
* If set to true, the plugin will try to tree-shake tracing statements out.
42+
* Note that the success of this depends on tree shaking generally being enabled in your build.
43+
* Attention: DO NOT enable this when you're using any performance monitoring-related SDK features (e.g. Sentry.startSpan()).
44+
*/
45+
excludeTracing?: boolean;
46+
47+
/**
48+
* If set to `true`, the plugin will attempt to tree-shake (remove) code related to the Sentry SDK's Session Replay Shadow DOM recording functionality.
49+
* Note that the success of this depends on tree shaking being enabled in your build tooling.
50+
*
51+
* This option is safe to be used when you do not want to capture any Shadow DOM activity via Sentry Session Replay.
52+
*/
53+
excludeReplayShadowDom?: boolean;
54+
55+
/**
56+
* If set to `true`, the plugin will attempt to tree-shake (remove) code related to the Sentry SDK's Session Replay `iframe` recording functionality.
57+
* Note that the success of this depends on tree shaking being enabled in your build tooling.
58+
*
59+
* You can safely do this when you do not want to capture any `iframe` activity via Sentry Session Replay.
60+
*/
61+
excludeReplayIframe?: boolean;
62+
63+
/**
64+
* If set to `true`, the plugin will attempt to tree-shake (remove) code related to the Sentry SDK's Session Replay's Compression Web Worker.
65+
* Note that the success of this depends on tree shaking being enabled in your build tooling.
66+
*
67+
* **Notice:** You should only do use this option if you manually host a compression worker and configure it in your Sentry Session Replay integration config via the `workerUrl` option.
68+
*/
69+
excludeReplayWorker?: boolean;
70+
};
71+
72+
export type SentryReactRouterPluginOptions = {
73+
/**
74+
* The auth token to use when uploading source maps to Sentry.
75+
*
76+
* Instead of specifying this option, you can also set the `SENTRY_AUTH_TOKEN` environment variable.
77+
*
78+
* To create an auth token, follow this guide:
79+
* @see https://docs.sentry.io/product/accounts/auth-tokens/#organization-auth-tokens
80+
*/
81+
authToken?: string;
82+
83+
/**
84+
* The organization slug of your Sentry organization.
85+
* Instead of specifying this option, you can also set the `SENTRY_ORG` environment variable.
86+
*/
87+
org?: string;
88+
89+
/**
90+
* The project slug of your Sentry project.
91+
* Instead of specifying this option, you can also set the `SENTRY_PROJECT` environment variable.
92+
*/
93+
project?: string;
94+
95+
/**
96+
* Options for the Sentry Vite plugin to customize bundle size optimizations.
97+
*/
98+
bundleSizeOptimizations?: BundleSizeOptimizationOptions;
99+
100+
/**
101+
* If this flag is `true`, Sentry will log debug information during build time.
102+
* @default false.
103+
*/
104+
debug?: boolean;
105+
106+
/**
107+
* Options for the Sentry Vite plugin to customize the source maps upload process.
108+
*
109+
*/
110+
sourceMapsUploadOptions?: SourceMapsOptions;
111+
112+
/**
113+
* Options to further customize the Sentry Vite Plugin (@sentry/vite-plugin) behavior directly.
114+
* Options specified in this object take precedence over the options specified in
115+
* the `sourcemaps` and `release` objects.
116+
*
117+
* @see https://www.npmjs.com/package/@sentry/vite-plugin/v/2.22.2#options which lists all available options.
118+
*
119+
* Warning: Options within this object are subject to change at any time.
120+
* We DO NOT guarantee semantic versioning for these options, meaning breaking
121+
* changes can occur at any time within a major SDK version.
122+
*
123+
* Furthermore, some options are untested with SvelteKit specifically. Use with caution.
124+
*/
125+
unstable_sentryVitePluginOptions?: Partial<SentryVitePluginOptions>;
126+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import type { Plugin } from 'vite';
2+
import { describe, expect, it, vi } from 'vitest';
3+
import { sentryReactRouter } from '../../src/vite/plugin';
4+
5+
vi.spyOn(console, 'log').mockImplementation(() => {
6+
/* noop */
7+
});
8+
vi.spyOn(console, 'warn').mockImplementation(() => {
9+
/* noop */
10+
});
11+
12+
function getSentryReactRouterVitePlugins(options?: Parameters<typeof sentryReactRouter>[0]): Plugin[] {
13+
return sentryReactRouter(
14+
{
15+
project: 'project',
16+
org: 'org',
17+
authToken: 'token',
18+
...options,
19+
},
20+
{},
21+
);
22+
}
23+
24+
describe('sentryReactRouter()', () => {
25+
it('returns an array of vite plugins', () => {
26+
const plugins = getSentryReactRouterVitePlugins();
27+
const names = plugins.map(plugin => plugin.name);
28+
expect(names).toEqual([
29+
'sentry-telemetry-plugin',
30+
'sentry-vite-release-injection-plugin',
31+
'sentry-release-management-plugin',
32+
'sentry-vite-debug-id-injection-plugin',
33+
'sentry-vite-debug-id-upload-plugin',
34+
'sentry-file-deletion-plugin',
35+
'sentry-react-router-update-source-map-setting',
36+
]);
37+
});
38+
});

0 commit comments

Comments
 (0)