@@ -20,7 +20,7 @@ import {
2020 normalizePath ,
2121 parseAstAsync ,
2222} from 'vite'
23- import { crawlFrameworkPkgs } from 'vitefu'
23+ import { crawlFrameworkPkgs , findClosestPkgJsonPath } from 'vitefu'
2424import vitePluginRscCore from './core/plugin'
2525import {
2626 type TransformWrapExportFilter ,
@@ -838,9 +838,42 @@ globalThis.AsyncLocalStorage = __viteRscAyncHooks.AsyncLocalStorage;
838838 ? [ validateImportPlugin ( ) ]
839839 : [ ] ) ,
840840 scanBuildStripPlugin ( ) ,
841+ detectNonOptimizedCjsPlugin ( ) ,
841842 ]
842843}
843844
845+ function detectNonOptimizedCjsPlugin ( ) : Plugin {
846+ return {
847+ name : 'rsc:detect-non-optimized-cjs' ,
848+ apply : 'serve' ,
849+ async transform ( code , id ) {
850+ if (
851+ id . includes ( '/node_modules/' ) &&
852+ ! id . startsWith ( this . environment . config . cacheDir ) &&
853+ / \b ( r e q u i r e | e x p o r t s ) \b / . test ( code )
854+ ) {
855+ id = parseIdQuery ( id ) . filename
856+ let isEsm = id . endsWith ( '.mjs' )
857+ if ( id . endsWith ( '.js' ) ) {
858+ const pkgJsonPath = await findClosestPkgJsonPath ( path . dirname ( id ) )
859+ if ( pkgJsonPath ) {
860+ const pkgJson = JSON . parse (
861+ fs . readFileSync ( pkgJsonPath , 'utf-8' ) ,
862+ ) as { type ?: string }
863+ isEsm = pkgJson . type === 'module'
864+ }
865+ }
866+ if ( ! isEsm ) {
867+ this . warn (
868+ `[vite-rsc] found non-optimized CJS dependency in '${ this . environment . name } ' environment. ` +
869+ `It is recommended to manually add the dependency to 'environments.${ this . environment . name } .optimizeDeps.include'.` ,
870+ )
871+ }
872+ }
873+ } ,
874+ }
875+ }
876+
844877function scanBuildStripPlugin ( ) : Plugin {
845878 return {
846879 name : 'rsc:scan-strip' ,
@@ -1900,7 +1933,7 @@ function evalValue<T = any>(rawValue: string): T {
19001933// https://github.com/vitejs/vite-plugin-vue/blob/06931b1ea2b9299267374cb8eb4db27c0626774a/packages/plugin-vue/src/utils/query.ts#L13
19011934function parseIdQuery ( id : string ) {
19021935 if ( ! id . includes ( '?' ) ) return { filename : id , query : { } }
1903- const [ filename , rawQuery ] = id . split ( `?` , 2 )
1936+ const [ filename , rawQuery ] = id . split ( `?` , 2 ) as [ string , string ]
19041937 const query = Object . fromEntries ( new URLSearchParams ( rawQuery ) )
19051938 return { filename, query }
19061939}
0 commit comments