Skip to content

[bug][vite-plugin-beasties] Build crashes with TypeError when using pruneSource: true and additionalStylesheets together #177

@Chrtyaka

Description

@Chrtyaka

Hi 👋🏻!
First off, thank you for creating and maintaining this very useful plugin!
Recently, I started using this plugin in my Vue project, just for experimentation. Spend a couple of hours debugging the issue with my build.

And I'd like to report a bug I encountered when using the pruneSource: true and additionalStylesheets options together. It appears to cause a TypeError that crashes the build process.

Description

When vite-plugin-beasties is configured with both the pruneSource: true and additionalStylesheets options, the Vite build process fails with a TypeError.

Steps to Reproduce

  1. Set up a standard Vite or Vue project (e.g., npm create vite@latest).
  2. Create a simple CSS file in the public directory (e.g., public/reset.css).
  3. Configure vite.config.js to use both pruneSource: true and additionalStylesheets: true
  4. run npm run build

Expected Behavior

The build should complete successfully. The critical CSS from reset.css should be inlined in the final index.html.

Actual behavior

The build process crashes with the following error:
vite-plugin-beasties error: TypeError: Cannot read properties of undefined (reading 'replace')

Simple reproduction link: https://stackblitz.com/edit/vitejs-vite-t3rl8zk5?file=vite.config.ts

Workaround

A viable workaround is to disable pruneSource. This avoids the crash, but the original source assets will not be pruned.

Suggested fix

Simply add $$name internal prop to the file when it is created in embedAdditionalStylesheet function.

    const styleSheetsIncluded: string[] = []

    const sources = await Promise.all(
      this.options.additionalStylesheets.map((cssFile) => {
        if (styleSheetsIncluded.includes(cssFile)) {
          return []
        }
        styleSheetsIncluded.push(cssFile)
        const style = document.createElement('style')
        style.$$external = true
        // add internal $$name property
        style.$$name = cssFile
        return this.getCssAsset(cssFile, style).then(sheet => [sheet, style] as const)
      }),
    )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions