css-custom-globals-loader
Exposes CSS globals like custom properties, custom media queries and custom selectors.
Recommended with postcss-preset-env, instructions below.
Usage
yarn add css-custom-globals-loader
Basic
Make sure to include it before css-loader:
// webpack.config.jsmoduleexports = // ... module: rules: test: /\.css$/ use: 'style-loader' 'css-custom-globals-loader' 'css-loader'
Write CSS containing globals:
/* style.css */ @); @
Import them into JavaScript:
// index.js console // 'lightblue'console // '(max-width: 30em)'console // 'h1'
With CSS Modules
When using CSS Modules, CSS globals will be exported along with class names in the same object.
// webpack.config.jsmoduleexports = // ... module: rules: test: /\.css$/ use: 'style-loader' 'css-custom-globals-loader' 'css-loader?modules'
/* style.css */
// index.js console // 'lightblue'console // '_23_aKvs-b8bW2Vg3fwHozO'
With CSS Modules and postcss-preset-env
yarn add postcss-loader postcss-preset-env
// webpack.config.jsmoduleexports = // ... module: rules: test: /\.css$/ use: 'style-loader' 'css-custom-globals-loader' 'css-loader?modules&importLoaders=1' 'postcss-loader'
Configure postcss-preset-env to use globals when compiling CSS files:
// postcss.config.jsmoduleexports = plugins: 'postcss-preset-env': // contents of this file will be available in every CSS file importFrom: 'globals.css' // enable all features, the default stage 2 // doesn't include features like custom media queries stage: 0 // don't strip off experimental features like custom media queries, // otherwise css-custom-globals-loader won't be able to expose them preserve: true
/* globals.css */@);
Now this custom media query and custom properties will be available in all CSS files:
/* style.css */ {}
// index.jsimport React from 'react'import customMedia customProperties from './globals.css'import styles from './style.css' const Image = <img = ="a kitten" ="kitten-200.jpg" ="kitten-200.jpg 200w, kitten-300.jpg 300w" = />
Always import your globals. Even if you're not sharing CSS globals with JavaScript, import globals.css
at least once in your app in order to ensure that its contents end up in your CSS. It's true that postcss-preset-env provides fallbacks for browsers that don't support custom properties, but those that do will try to use them and fail if they don't exist.
Despite its name, importFrom
doesn't actually import that file, postcss-preset-env only uses it to provide fallbacks. This is why you need to import it as a module yourself.
Caveats
Exposing globals and class names in the same object is not ideal because if we were to use the class name .customProperties
, it would get overwritten with the customProperties
object and we would be unable to access it.