Skip to content

Abnormal behaviors in building worker modules. #15310

@XiSenao

Description

@XiSenao

Describe the bug

When handling worker modules, Vite uses Rollup for building, and the default target output is iife. However, an interesting issue #15305 was discovered when the target output is iife and there is an exception in handling the statement by Rollup.

// Before compiling worker.js 
const t = import.meta && import.meta.url && new URL(import.meta.url)

// After compiling worker.js
var e = typeof document < "u" ? document.currentScript : null;
const t = {
    url: e && e.src || new URL("assets/worker-mLIARZvR.js",document.baseURI).href
} && self.location.href && new URL(self.location.href);

There will definitely be an issue in worker modules because the document instance cannot be accessed within worker. It behaves correctly when the target output is es. This also creates a differentiation between the development stage and the build stage, so some additional handling may be required in this case.

Reproduction

https://stackblitz.com/edit/vitejs-vite-bryjvn?file=index.html

Steps to reproduce

pnpm install && pnpm build && pnpm preview

System Info

System:
    OS: macOS 14.1.2
    CPU: (8) arm64 Apple M1
    Memory: 48.72 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.12.0 - ~/.nvm/versions/node/v18.12.0/bin/node
    Yarn: 1.22.17 - /opt/homebrew/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v18.12.0/bin/npm
    pnpm: 8.11.0 - ~/.nvm/versions/node/v18.12.0/bin/pnpm
    bun: 1.0.14 - ~/.bun/bin/bun
  Browsers:
    Chrome: 120.0.6099.71
    Safari: 17.1.2
  npmPackages:
    @vitejs/plugin-react-swc: ^3.5.0 => 3.5.0 
    vite: ^5.0.0 => 5.0.7

Used Package Manager

pnpm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    feat: web workersp3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions