1313const fs = require ( "fs" ) ;
1414const path = require ( "path" ) ;
1515
16- exports . WasmPlugin = function WasmPlugin ( inline ) {
16+ exports . WasmPlugin = function WasmPlugin ( inline , webpack_hack ) {
1717 function setup ( build ) {
1818 const options = build . initialOptions ;
1919 options . metafile = true ;
@@ -62,12 +62,14 @@ exports.WasmPlugin = function WasmPlugin(inline) {
6262 . toString ( )
6363 . slice ( 2 ) } __`;
6464 KEYSET . push ( key ) ;
65+ const url = webpack_hack ? `${ key } (wasm)` : `wasm` ;
66+
6567 return {
6668 pluginData : args . pluginData ,
6769 contents : `
6870 import wasm from ${ JSON . stringify ( args . path ) } ;
6971 export default function() {
70- return fetch(new URL(${ key } (wasm) , import.meta.url));
72+ return fetch(new URL(${ url } , import.meta.url));
7173 };
7274 ` ,
7375 } ;
@@ -84,39 +86,42 @@ exports.WasmPlugin = function WasmPlugin(inline) {
8486 } ) ;
8587
8688 build . onEnd ( ( { metafile } ) => {
87- for ( const file of Object . keys ( metafile . outputs ) ) {
88- if ( file . endsWith ( ".js" ) ) {
89- let contents = fs . readFileSync ( file ) . toString ( ) ;
90- let updated = false ;
91- for ( const key of KEYSET ) {
92- const symbol = contents . match (
93- new RegExp ( `${ key } \\(([a-zA-Z0-9_\$]+?)\\)` )
94- ) ;
95-
96- if ( symbol ?. [ 1 ] ) {
97- updated = true ;
98- const escapedSymbol = symbol [ 1 ] . replace (
99- / \$ / g,
100- "\\$"
101- ) ;
102- const filename = contents . match (
103- new RegExp (
104- `${ escapedSymbol } \\s*?=\\s*?\\"(.+?)\\"`
105- )
89+ if ( webpack_hack ) {
90+ for ( const file of Object . keys ( metafile . outputs ) ) {
91+ if ( file . endsWith ( ".js" ) ) {
92+ let contents = fs . readFileSync ( file ) . toString ( ) ;
93+ let updated = false ;
94+ for ( const key of KEYSET ) {
95+ const symbol = contents . match (
96+ new RegExp ( `${ key } \\(([a-zA-Z0-9_\$]+?)\\)` )
10697 ) ;
10798
108- contents = contents . replace (
109- new RegExp (
110- `${ key } \\(([a-zA-Z0-9_\$]+?)\\)` ,
111- "g"
112- ) ,
113- `"${ filename [ 1 ] } "`
114- ) ;
99+ if ( symbol ?. [ 1 ] ) {
100+ updated = true ;
101+ const escapedSymbol = symbol [ 1 ] . replace (
102+ / \$ / g,
103+ "\\$"
104+ ) ;
105+
106+ const filename = contents . match (
107+ new RegExp (
108+ `(?<![a-zA-Z0-9_\$])${ escapedSymbol } \\s*?=\\s*?\\"(.+?)\\"`
109+ )
110+ ) ;
111+
112+ contents = contents . replace (
113+ new RegExp (
114+ `${ key } \\(([a-zA-Z0-9_\$]+?)\\)` ,
115+ "g"
116+ ) ,
117+ `"${ filename [ 1 ] } "`
118+ ) ;
119+ }
115120 }
116- }
117121
118- if ( updated ) {
119- fs . writeFileSync ( file , contents ) ;
122+ if ( updated ) {
123+ fs . writeFileSync ( file , contents ) ;
124+ }
120125 }
121126 }
122127 }
0 commit comments