Repository: vitejs/vite
File: packages/vite/src/node/optimizer/rolldownDepPlugin.ts (TypeScript)

Code before:
            key !== 'splice'
        ) {
            console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
        }
        }
    }))`,
              }
            }
          }

          if (id.startsWith(optionalPeerDepNamespace)) {
            const path = id.slice(optionalPeerDepNamespace.length)
            const [, peerDep, parentDep] = path.split(':')
            return {
              code:
                'module.exports = {};' +
                `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
            }
          }
        },
      },
      transform: {
        filter: { code: /new\s+URL/ },
        async handler(code, id) {
          if (!id.includes('node_modules')) return null

          const s = new MagicString(code)

          const workerRE =
            /(new\s+(?:Shared)?Worker\s*\(\s*)new\s+URL\s*\(\s*(['"])((?:(?!\2).|\\.)*)\2\s*,\s*import\.meta\.url\s*\)/g

          // Optimized dependencies are always written to the 'deps' sub-directory
          // within the configured cache directory.
          const bundleDir = path.join(environment.config.cacheDir, 'deps')

          let hasReplacements = false
          let match
          while ((match = workerRE.exec(code))) {
            hasReplacements = true
            const [fullMatch, prefix, _, url] = match
            const absolutePath = path.resolve(path.dirname(id), url)
            const relativePath = path.relative(bundleDir, absolutePath)
            const normalizedRelativePath = normalizePath(relativePath)

            // NOTE: add `'' +` to opt-out rolldown's transform: https://github.com/rolldown/rolldown/issues/2745
            const replacement = `${prefix}new URL('' + ${JSON.stringify(normalizedRelativePath)}, import.meta.url)`

            s.overwrite(
              match.index,
              match.index + fullMatch.length,
              replacement,

Review comment (performance):
```suggestion
```
If the file is bundled by the optimizer, I think we need to resolve the path in `new URL`.

Code after:
        get(_, key) {
        if (
            key !== '__esModule' &&
            key !== '__proto__' &&
            key !== 'constructor' &&
            key !== 'splice'
        ) {
            console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
        }
        }
    }))`,
              }
            }
          }

          if (id.startsWith(optionalPeerDepNamespace)) {
            const path = id.slice(optionalPeerDepNamespace.length)
            const [, peerDep, parentDep] = path.split(':')
            return {
              code:
                'module.exports = {};' +
                `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
            }
          }
        },
      },
      transform: {
        filter: {
          code: /new\s+URL.+import\.meta\.url/s,
        },
        async handler(code, id) {
          let s: MagicString | undefined
          const assetImportMetaUrlRE =
            /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg
          const cleanString = stripLiteral(code)

          let match: RegExpExecArray | null
          while ((match = assetImportMetaUrlRE.exec(cleanString))) {
            const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices!
            if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue

            const rawUrl = code.slice(urlStart, urlEnd)

            if (rawUrl[0] === '`' && rawUrl.includes('${')) {
              // We skip dynamic template strings in the optimizer for now as they
              // require complex glob transformation that is handled by the main asset plugin.
              continue
            }

            const url = rawUrl.slice(1, -1)
            if (isDataUrl(url) || isExternalUrl(url) || url.startsWith('/')) {