A Vite plugin for handling CSS sourcemaps. This plugin ensures that CSS sourcemaps are properly generated and referenced in your Vite builds.
- Automatically generates sourcemaps for CSS files
- Supports custom sourcemap file locations
- Configurable sourcemap URL generation
- Works with Vite's build process
- Compatible with Vite 5.x and 6.x
npm install vite-plugin-css-sourcemap --save-dev # or yarn add vite-plugin-css-sourcemap --dev # or pnpm add vite-plugin-css-sourcemap --save-devAdd the plugin to your Vite configuration:
// vite.config.js import { defineConfig } from 'vite'; import cssSourcemap from 'vite-plugin-css-sourcemap'; export default defineConfig({ plugins: [cssSourcemap()], });The plugin accepts the following options:
cssSourcemap({ // Enable/disable the plugin enabled: true, // Custom extensions to process (default: ['.css', '.scss']) extensions: ['.css', '.scss', '.less'], // Custom folder for sourcemap files folder: 'sourcemaps', // Custom function to generate sourcemap URLs getURL: (fileName) => `sourcemaps/${fileName}`, });| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable or disable the plugin |
extensions | string[] | ['.css', '.scss'] | File extensions to process |
folder | string | '' | Custom folder for sourcemap files |
getURL | (fileName: string) => string | (fileName) => fileName | Custom function to generate sourcemap URLs |
// vite.config.js import { defineConfig } from 'vite'; import cssSourcemap from 'vite-plugin-css-sourcemap'; export default defineConfig({ plugins: [cssSourcemap()], });// vite.config.js import { defineConfig } from 'vite'; import cssSourcemap from 'vite-plugin-css-sourcemap'; export default defineConfig({ plugins: [ cssSourcemap({ folder: 'sourcemaps', }), ], });// vite.config.js import { defineConfig } from 'vite'; import cssSourcemap from 'vite-plugin-css-sourcemap'; export default defineConfig({ plugins: [ cssSourcemap({ getURL: (fileName) => `/assets/sourcemaps/${fileName}`, }), ], });// vite.config.js import { defineConfig } from 'vite'; import cssSourcemap from 'vite-plugin-css-sourcemap'; export default defineConfig({ plugins: [ cssSourcemap({ extensions: ['.css', '.scss', '.less'], }), ], });This plugin hooks into Vite's build process to:
- Intercept CSS file processing
- Generate sourcemaps for CSS files
- Emit the sourcemap files to the output directory
- Add sourcemap references to the CSS files
The plugin works by:
- Using the
transformhook to process CSS files and generate sourcemaps - Using the
generateBundlehook to ensure sourcemaps are properly emitted - It observes
vite:css-postplugin, specifically theaugmentChunkHashhook to obtain the future id of the file. - Allows configuring the sourcemap URL based on the provided options
This plugin is compatible with:
- Vite 5.x
- Vite 6.x
MIT