Skip to content

Passing file info to postcss ctx.file #22398

@Airkro

Description

@Airkro

Description

PostCSS plugins rely on ctx.file to access file-specific context (like path and metadata) during CSS processing. In Vite's current build process, this property is undefined, creating a compatibility gap with Webpack and Rollup.
This affects plugins that need to:

  • Access the current CSS file's path
  • Perform path-based calculations (e.g., for relative imports)
  • Generate file-specific metadata or cache keys
  • Apply conditional logic based on file location or name

The issue forces developers to avoid dependent plugins, implement fragile workarounds, or face migration hurdles when moving from Webpack/Rollup to Vite.

Benefits & Use Cases

With ctx.file implemented:

  • Path resolution: Plugins can accurately resolve relative paths for assets or imports.
  • File-specific logic: Plugins can apply transformations conditionally based on file attributes or directories.
  • Seamless migration: Plugins working in Webpack/Rollup will function identically in Vite.
  • Better debugging: Error messages can include the problematic file's path.
  • Enhanced capabilities: Supports advanced plugins for source maps, caching, or file-specific outputs.

This completes Vite's PostCSS integration, supporting the full PostCSS plugin ecosystem.

Suggested solution

Vite should properly implement the PostCSS API by:

  1. Providing the from option: Pass the absolute path of the CSS file to postcss.process().
  2. Populating ctx.file: Ensure the PostCSS context includes a valid file property with the source file's absolute path and metadata.
  3. Ensuring consistency: Match the behavior of Webpack (postcss-loader) and Rollup's PostCSS integration.
  4. Supporting all modes: Work consistently in both development server and production builds.

The implementation should be transparent—no user configuration changes required—enabling existing plugins that use ctx.file to work automatically.

Alternative

No response

Additional context

  • References: Webpack's postcss-loader and Rollup's PostCSS plugin demonstrate correct implementation.
  • PostCSS API: The from option is documented as the method to provide file context to plugins.
  • Ecosystem impact: Popular plugins (e.g., autoprefixer, postcss-import) depend on ctx.file. Full compatibility benefits the Vite ecosystem.
  • Migration: Fixing this eliminates a key barrier for projects transitioning from Webpack/Rollup.

Similar issues exists but closed and locked

Validations

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions