css-variables-loader
raw JSON → 2.0.2 verified Sat Apr 25 auth: no javascript
A Webpack loader that extracts CSS custom properties (variables) from CSS files and makes them available as a JavaScript object map. Version 2.0.2 is the latest stable release. It only supports variables defined on the `:root` selector and requires a Webpack-based build setup. Unlike CSS-modules or other approaches, this loader provides a simple key-value export of CSS variable names to their string values, facilitating dynamic theme or configuration use.
Common errors
error Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type. ↓
cause Attempting to import a CSS file without the loader in the import path.
fix
Add the loader prefix:
import variables from 'css-variables-loader!./variables.css'; error Cannot find module 'css-variables-loader' ↓
cause The loader is not installed or not listed in devDependencies.
fix
Run
npm install --save-dev css-variables-loader Warnings
gotcha Only variables defined on the `:root` selector are extracted. ↓
fix Ensure all desired CSS custom properties are declared under `:root { ... }`. Variables in other selectors or @media blocks are ignored.
gotcha This loader is Webpack-specific and cannot be used in other bundlers like Rollup or Parcel. ↓
fix Use an alternative solution such as `postcss-custom-properties` with Rollup or a similar bundler-specific plugin.
gotcha The loader outputs string values; numeric or unit values like `18px` remain strings. ↓
fix Parse numeric values manually if needed: `parseInt(variables['--my-font-size'], 10)` or use a helper library.
Install
npm install css-variables-loader yarn add css-variables-loader pnpm add css-variables-loader Imports
- default wrong
const variables = require('css-variables-loader!./variables.css');correctimport variables from 'css-variables-loader!./variables.css'; - default wrong
require('!css-variables!./variables.css')correctrequire('css-variables-loader!./variables.css') - named exports wrong
import { '--my-theme-color' } from 'css-variables-loader!./variables.css';correctimport * as variables from 'css-variables-loader!./variables.css';
Quickstart
// Install: npm install --save-dev css-variables-loader
// In your JavaScript file:
import variables from 'css-variables-loader!./variables.css';
console.log(variables);
// Output: { '--my-theme-color': 'hsl(121, 90%, 90%)', '--my-accent-color': 'hsl(60, 90%, 90%)', '--my-font-size': '18px' }