@@ -12,11 +12,17 @@ import {
1212 SHEBANG_PREFIX ,
1313 SHEBANG_REGEX ,
1414} from '../constant' ;
15- import { importMetaUrlShim } from './shims' ;
1615const require = createRequire ( import . meta. url ) ;
1716
1817const PLUGIN_NAME = 'rsbuild:lib-entry-chunk' ;
1918const LOADER_NAME = 'rsbuild:lib-entry-module' ;
19+ const IMPORT_META_URL_SHIM = `const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
20+ return typeof document === 'undefined'
21+ ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
22+ : (document.currentScript && document.currentScript.src) ||
23+ new URL('main.js', document.baseURI).href;
24+ })();
25+ ` ;
2026
2127const matchFirstLine = ( source : string , regex : RegExp ) : string | false => {
2228 const lineBreakPos = source . match ( / ( \r \n | \n ) / ) ;
@@ -32,6 +38,8 @@ const matchFirstLine = (source: string, regex: RegExp): string | false => {
3238class EntryChunkPlugin {
3339 private reactDirectives : Record < string , string > = { } ;
3440
41+ private shimsInjectedAssets : Set < string > = new Set ( ) ;
42+
3543 private shebangChmod = 0o755 ;
3644 private shebangEntries : Record < string , string > = { } ;
3745 private shebangInjectedAssets : Set < string > = new Set ( ) ;
@@ -101,6 +109,8 @@ class EntryChunkPlugin {
101109 const name = chunk . name ;
102110 if ( ! name ) return ;
103111
112+ this . shimsInjectedAssets . add ( filename ) ;
113+
104114 const shebangEntry = this . shebangEntries [ name ] ;
105115 if ( shebangEntry ) {
106116 this . shebangEntries [ filename ] = shebangEntry ;
@@ -117,9 +127,13 @@ class EntryChunkPlugin {
117127 compilation . hooks . processAssets . tap ( PLUGIN_NAME , ( assets ) => {
118128 if ( ! this . enabledImportMetaUrlShim ) return ;
119129
120- const chunkAsset = Object . keys ( assets ) . filter ( ( name ) =>
121- JS_EXTENSIONS_PATTERN . test ( name ) ,
122- ) ;
130+ const chunkAsset = Object . keys ( assets ) . filter ( ( name ) => {
131+ return (
132+ JS_EXTENSIONS_PATTERN . test ( name ) &&
133+ this . shimsInjectedAssets . has ( name )
134+ ) ;
135+ } ) ;
136+
123137 for ( const name of chunkAsset ) {
124138 compilation . updateAsset ( name , ( old ) => {
125139 const oldSource = old . source ( ) . toString ( ) ;
@@ -131,10 +145,10 @@ class EntryChunkPlugin {
131145 replaceSource . replace (
132146 0 ,
133147 11 , // 'use strict;'.length,
134- `"use strict";\n${ importMetaUrlShim } ` ,
148+ `"use strict";\n${ IMPORT_META_URL_SHIM } ` ,
135149 ) ;
136150 } else {
137- replaceSource . insert ( 0 , importMetaUrlShim ) ;
151+ replaceSource . insert ( 0 , IMPORT_META_URL_SHIM ) ;
138152 }
139153
140154 return replaceSource ;
0 commit comments