vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
67.33k stars 6.06k forks source link

[vite:plugin-legacy] Polyfills fail to load when using <base href... /> #18154

Open pongells opened 1 day ago

pongells commented 1 day ago

Describe the bug

Polyfills are attached to index.html as first thing in <head>, this means they are loaded before <base href.. /> is set.

In my case this results in:

  <head>
    <script type="module" crossorigin src="./assets/polyfills-BFgdcrnO.js"></script>

    <base href="/" />
    <meta charset="utf-8" />
   ....

which is wrong.

Reproduction

https://github.com/pongells/vite-legacy-repro

Steps to reproduce

Checkout repo then:

npm install
npm run build
npm run preview

Go to:

http://localhost:4173/about/me

see polyfills not being loaded.

Summary:

System Info

System:
    OS: macOS 14.6.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 8.78 GB / 64.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.0 - ~/.n/bin/node
    Yarn: 4.4.1 - /opt/homebrew/bin/yarn
    npm: 8.18.0 - /opt/homebrew/bin/npm
    pnpm: 7.33.6 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 129.0.6668.59
    Safari: 17.6
  npmPackages:
    @vitejs/plugin-legacy: ^5.4.2 => 5.4.2 
    @vitejs/plugin-react: 4.3.1 => 4.3.1 
    @vitejs/plugin-react-swc: 3.7.0 => 3.7.0 
    rollup: 4.22.0 => 4.22.0 
    vite: 5.4.6 => 5.4.6

Used Package Manager

yarn

Logs

No response

Validations

pongells commented 1 day ago

Very very hacky workaround with a custom plugin:

 {
      name: "reorder-base-script",
      transformIndexHtml(html) {
        return html.replace(
          /(<head>)([\s\S]*?)(<script type="module" crossorigin src="\.\/assets\/polyfills[^"]+"><\/script>)([\s\S]*?)(<base href="[^"]+" \/>)/,
          (match, headOpen, headContent, scriptTag, rest, baseTag) => {
            return `${headOpen}\n    ${baseTag}\n    ${headContent.trim()}\n    ${scriptTag}`;
          },
        );
      },
      apply: "build",
      enforce: "post",
    },

probably can be simplified a bit..