Skip to content

Commit 25b652b

Browse files
authored
feat: silence "use client" warning (#144)
1 parent fbf722f commit 25b652b

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

packages/plugin-react/src/index.ts

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import type { ParserOptions, TransformOptions } from '@babel/core'
22
import * as babel from '@babel/core'
33
import { createFilter } from 'vite'
4-
import type { Plugin, PluginOption, ResolvedConfig } from 'vite'
4+
import type {
5+
BuildOptions,
6+
Plugin,
7+
PluginOption,
8+
ResolvedConfig,
9+
UserConfig,
10+
} from 'vite'
511
import MagicString from 'magic-string'
612
import type { SourceMap } from 'magic-string'
713
import {
@@ -268,7 +274,8 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
268274
const viteReactRefresh: Plugin = {
269275
name: 'vite:react-refresh',
270276
enforce: 'pre',
271-
config: () => ({
277+
config: (userConfig) => ({
278+
build: silenceUseClientWarning(userConfig),
272279
optimizeDeps: {
273280
// We can't add `react-dom` because the dependency is `react-dom/client`
274281
// for React 18 while it's `react-dom` for React 17. We'd need to detect
@@ -306,6 +313,24 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
306313

307314
viteReact.preambleCode = preambleCode
308315

316+
const silenceUseClientWarning = (userConfig: UserConfig): BuildOptions => ({
317+
rollupOptions: {
318+
onwarn(warning, defaultHandler) {
319+
if (
320+
warning.code === 'MODULE_LEVEL_DIRECTIVE' &&
321+
warning.message.includes('use client')
322+
) {
323+
return
324+
}
325+
if (userConfig.build?.rollupOptions?.onwarn) {
326+
userConfig.build.rollupOptions.onwarn(warning, defaultHandler)
327+
} else {
328+
defaultHandler(warning)
329+
}
330+
},
331+
},
332+
})
333+
309334
const loadedPlugin = new Map<string, any>()
310335
function loadPlugin(path: string): any {
311336
const cached = loadedPlugin.get(path)

0 commit comments

Comments
 (0)