@@ -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,45 @@ 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+ ( code . includes ( 'exports' ) || code . includes ( 'require' ) )
854+ ) {
855+ id = parseIdQuery ( id ) . filename
856+ let isCjs = id . endsWith ( '.cjs' )
857+ if ( ! isCjs && id . endsWith ( '.js' ) ) {
858+ // check closest package.json
859+ const pkgJsonPath = await findClosestPkgJsonPath ( path . dirname ( id ) )
860+ if ( pkgJsonPath ) {
861+ const pkgJson = JSON . parse (
862+ fs . readFileSync ( pkgJsonPath , 'utf-8' ) ,
863+ ) as { type ?: string }
864+ isCjs = pkgJson . type !== 'module'
865+ } else {
866+ isCjs = true
867+ }
868+ }
869+ if ( isCjs ) {
870+ this . warn (
871+ `[vite-rsc] found non-optimized CJS dependency in '${ this . environment . name } ' environment. ` +
872+ `It is recommended to manually add the dependency to 'environments.${ this . environment . name } .optimizeDeps.include'.` ,
873+ )
874+ }
875+ }
876+ } ,
877+ }
878+ }
879+
844880function scanBuildStripPlugin ( ) : Plugin {
845881 return {
846882 name : 'rsc:scan-strip' ,
@@ -1900,7 +1936,7 @@ function evalValue<T = any>(rawValue: string): T {
19001936// https://github.com/vitejs/vite-plugin-vue/blob/06931b1ea2b9299267374cb8eb4db27c0626774a/packages/plugin-vue/src/utils/query.ts#L13
19011937function parseIdQuery ( id : string ) {
19021938 if ( ! id . includes ( '?' ) ) return { filename : id , query : { } }
1903- const [ filename , rawQuery ] = id . split ( `?` , 2 )
1939+ const [ filename , rawQuery ] = id . split ( `?` , 2 ) as [ string , string ]
19041940 const query = Object . fromEntries ( new URLSearchParams ( rawQuery ) )
19051941 return { filename, query }
19061942}
0 commit comments