From 80fb15a32de4b0ece39fc830ac20bd60da6d2877 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arnaud=20Barr=C3=A9?= Date: Wed, 5 Apr 2023 17:49:27 +0200 Subject: [PATCH] feat: silence "use client" warning --- packages/plugin-react/src/index.ts | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/plugin-react/src/index.ts b/packages/plugin-react/src/index.ts index 50e2377b..f395585f 100644 --- a/packages/plugin-react/src/index.ts +++ b/packages/plugin-react/src/index.ts @@ -1,7 +1,13 @@ import type { ParserOptions, TransformOptions } from '@babel/core' import * as babel from '@babel/core' import { createFilter } from 'vite' -import type { Plugin, PluginOption, ResolvedConfig } from 'vite' +import type { + BuildOptions, + Plugin, + PluginOption, + ResolvedConfig, + UserConfig, +} from 'vite' import MagicString from 'magic-string' import type { SourceMap } from 'magic-string' import { @@ -268,7 +274,8 @@ export default function viteReact(opts: Options = {}): PluginOption[] { const viteReactRefresh: Plugin = { name: 'vite:react-refresh', enforce: 'pre', - config: () => ({ + config: (userConfig) => ({ + build: silenceUseClientWarning(userConfig), optimizeDeps: { // We can't add `react-dom` because the dependency is `react-dom/client` // 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[] { viteReact.preambleCode = preambleCode +const silenceUseClientWarning = (userConfig: UserConfig): BuildOptions => ({ + rollupOptions: { + onwarn(warning, defaultHandler) { + if ( + warning.code === 'MODULE_LEVEL_DIRECTIVE' && + warning.message.includes('use client') + ) { + return + } + if (userConfig.build?.rollupOptions?.onwarn) { + userConfig.build.rollupOptions.onwarn(warning, defaultHandler) + } else { + defaultHandler(warning) + } + }, + }, +}) + const loadedPlugin = new Map() function loadPlugin(path: string): any { const cached = loadedPlugin.get(path)