@@ -46,7 +46,7 @@ While it works great in `build` mode (because rollup is used), there is some iss
4646
4747There are workarounds for both:
4848
49- - We can help vite by replacing ` import.meta.url ` by the original module path:
49+ - We can help vite by replacing ` import.meta.url ` by the original module path (you need the --experimental-import-meta-resolve note option) :
5050``` typescript
5151{
5252 ...
@@ -56,13 +56,25 @@ There are workarounds for both:
5656 name: ' import.meta.url' ,
5757 setup ({ onLoad }) {
5858 // Help vite that bundles/move files in dev mode without touching `import.meta.url` which breaks asset urls
59- onLoad ({ filter: / . * \. js/ , namespace: ' file' }, args => {
60- let code = fs .readFileSync (args .path , ' utf8' )
61- code = code .replace (
62- / \b import\. meta\. url\b / g ,
63- ` new URL('/@fs${args .path }', window.location.origin) `
64- )
65- return { contents: code }
59+ onLoad ({ filter: / . * \. js/ , namespace: ' file' }, async args => {
60+ const code = fs .readFileSync (args .path , ' utf8' )
61+
62+ const assetImportMetaUrlRE = / \b new\s + URL\s * \( \s * ('[^ '] + '| "[^ "] + "| `[^ `] + `)\s * ,\s * import\. meta\. url\s * (?:,\s * )? \) / g
63+ let i = 0
64+ let newCode = ' '
65+ for (let match = assetImportMetaUrlRE .exec (code ); match != null ; match = assetImportMetaUrlRE .exec (code )) {
66+ newCode += code .slice (i , match .index )
67+
68+ const path = match [1 ].slice (1 , - 1 )
69+ const resolved = await import .meta .resolve !(path , url .pathToFileURL (args .path ))
70+
71+ newCode += ` new URL(${JSON .stringify (url .fileURLToPath (resolved ))}, import.meta.url) `
72+
73+ i = assetImportMetaUrlRE .lastIndex
74+ }
75+ newCode += code .slice (i )
76+
77+ return { contents: newCode }
6678 })
6779 }
6880 }]
0 commit comments