Skip to content

Commit f97ee48

Browse files
authored
fix(webpack): Make webpack import lazy to support rspack-only projects (#940)
1 parent 105f25a commit f97ee48

1 file changed

Lines changed: 25 additions & 3 deletions

File tree

  • packages/bundler-plugins/src/webpack

packages/bundler-plugins/src/webpack/index.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import type { SentryWebpackPluginOptions } from "./webpack4and5";
22
import { sentryWebpackPluginFactory } from "./webpack4and5";
3-
import * as webpack4or5 from "webpack";
3+
import { createRequire } from "node:module";
44

5-
const BannerPlugin = webpack4or5?.BannerPlugin || webpack4or5?.default?.BannerPlugin;
5+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
6+
type PluginClass = new (options: any) => unknown;
7+
8+
type WebpackModule = {
9+
BannerPlugin?: PluginClass;
10+
DefinePlugin?: PluginClass;
11+
default?: WebpackModule;
12+
};
13+
14+
// `webpack` is an optional peer dependency. We require it lazily so the plugin doesn't
15+
// crash on load in bundlers that don't ship `webpack` (e.g. rspack) — those provide
16+
// the plugin classes via `compiler.webpack` at runtime instead.
17+
function loadWebpack(): WebpackModule {
18+
try {
19+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
20+
// @ts-ignore Rollup transpiles import.meta for CJS
21+
return createRequire(import.meta.url)("webpack") as WebpackModule;
22+
} catch {
23+
return {};
24+
}
25+
}
626

7-
const DefinePlugin = webpack4or5?.DefinePlugin || webpack4or5?.default?.DefinePlugin;
27+
const webpack = loadWebpack();
28+
const BannerPlugin = webpack.BannerPlugin ?? webpack.default?.BannerPlugin;
29+
const DefinePlugin = webpack.DefinePlugin ?? webpack.default?.DefinePlugin;
830

931
// eslint-disable-next-line @typescript-eslint/no-explicit-any
1032
export const sentryWebpackPlugin: (options?: SentryWebpackPluginOptions) => any =

0 commit comments

Comments
 (0)