Skip to content

CSS referenced assets are included even when the file is tree shaken #9073

@Csszabi98

Description

@Csszabi98

Describe the bug

When a vite build includes a css file conditionally bound to environment variables the referenced assets by the CSS file always end up in the assets output folder even when the CSS file itself which references them does not.

index.css

@font-face {
    font-family: 'Roboto Regular';
    src: url('assets/roboto-regular.woff2') format('woff2');
    font-weight: normal;
    font-display: swap;
}

.env

VITE_INCLUDE_CSS="false"

index.js

if(import.meta.env.VITE_INCLUDE_CSS === 'true') {
  import('./index.css')
}

Expected behavior: index.css and roboto-regular.woff2 are not included in the build output folder.
Actual behavior: roboto-regular.woff2 is included in the build output folder.

Reproduction

https://github.com/Csszabi98/css-tree-shake-asset-issue

System Info

System:
    OS: macOS 12.4
    CPU: (10) x64 Apple M1 Pro
    Memory: 29.74 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 14.19.1 - ~/Library/Caches/fnm_multishells/957_1657095588762/bin/node
    npm: 6.14.16 - ~/Library/Caches/fnm_multishells/957_1657095588762/bin/npm
  Browsers:
    Brave Browser: 101.1.38.109
    Chrome: 103.0.5060.114
    Firefox: 101.0.1
    Safari: 15.5
  npmPackages:
    @vitejs/plugin-vue: ^2.3.3 => 2.3.3 
    vite: ^2.9.9 => 2.9.14

Used Package Manager

npm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions