### Start Website Development Server Source: https://github.com/parcel-bundler/lightningcss/blob/master/CONTRIBUTING.md Start the development server for the project's website, which is built using Parcel. ```shell yarn website:start ``` -------------------------------- ### Install Lightning CSS Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Install the lightningcss package as a development dependency using npm. ```shell npm install --save-dev lightningcss ``` -------------------------------- ### Install WASM Build Toolchain Source: https://github.com/parcel-bundler/lightningcss/blob/master/CONTRIBUTING.md Install the necessary toolchain and binaries for building the WebAssembly target, including the Rust target and wasm-opt. ```shell rustup target add wasm32-unknown-unknown cargo install wasm-opt ``` -------------------------------- ### Media Query Example Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/index.html This example demonstrates a media query with specific width constraints and important overrides. It's useful for responsive design adjustments. ```css @media (width < 700px) { .warp .bars { right: 5px !important; } .warp .bars .label { left: auto !important; right: 5px; color: black; } } ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/parcel-bundler/lightningcss/blob/master/CONTRIBUTING.md Clone the forked repository locally and install the project dependencies using Yarn. ```shell git clone https://github.com/USERNAME/lightningcss.git cd lightningcss yarn install ``` -------------------------------- ### Install Lightning CSS CLI Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Install the lightningcss-cli package as a development dependency for standalone CSS processing. ```shell npm install --save-dev lightningcss-cli ``` -------------------------------- ### Multiply Length Values by 2 Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md This example demonstrates how to use the `Length` visitor to double the value of all length units in a CSS rule. Ensure the `lightningcss` package is installed. ```javascript import { transform } from 'lightningcss'; let res = transform({ filename: 'test.css', minify: true, code: Buffer.from(` .foo { width: 12px; } `), visitor: { Length(length) { return { unit: length.unit, value: length.value * 2 } } } }); assert.equal(res.code.toString(), '.foo{width:24px}'); ``` -------------------------------- ### Bundling Order Example Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/bundling.md Demonstrates how Lightning CSS handles duplicate `@import` rules, following the browser behavior where the last instance of an imported file applies. ```css /* index.css */ @import "a.css"; @import "b.css"; @import "a.css"; ``` ```css /* a.css */ body { background: green } ``` ```css /* b.css */ body { background: red } ``` ```css body { background: green } ``` -------------------------------- ### Composing and Using Visitor Plugins Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Import and compose multiple visitor plugins using `composeVisitors` to apply them to CSS transformations. This example combines an environment variable visitor and a double function visitor. ```js import { transform, composeVisitors } from 'lightningcss'; import environmentVisitor from 'lightningcss-plugin-environment'; import doubleFunctionVisitor from 'lightningcss-plugin-double-function'; let res = transform({ filename: 'test.css', minify: true, code: Buffer.from(` .foo { padding: double(env(--branding-padding)); } `), visitor: composeVisitors([ environmentVisitor({ '--branding-padding': { type: 'length', value: { unit: 'px', value: 20 } } }), doubleFunctionVisitor ]) }); assert.equal(res.code.toString(), '.foo{padding:40px}'); ``` -------------------------------- ### CSS Grid Example with Scoped Areas and Columns Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Illustrates CSS grid layout with scoped `grid-template-areas` and `grid-column-start` properties, demonstrating the effect of naming patterns. ```css .grid { grid-template-areas: 'nav main'; } .nav { grid-column-start: nav-start; } ``` -------------------------------- ### CLI Script for CSS Compilation Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Example package.json script to compile, minify, and bundle CSS using the lightningcss CLI. ```json { "scripts": { "build": "lightningcss --minify --bundle --targets \">= 0.25%\" input.css -o output.css" } } ``` -------------------------------- ### Install lightningcss and css-minimizer-webpack-plugin Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Install the necessary packages for using Lightning CSS with webpack. This includes the core lightningcss package, the webpack plugin, and browserslist. ```shell npm install --save-dev lightningcss css-minimizer-webpack-plugin browserslist ``` -------------------------------- ### Color Transpilation Example Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/index.html Shows the input CSS with modern color functions and the output after transpilation to more compatible formats like hex, display-p3, and lab. This enables the use of future color features today. ```css .foo { color: oklab(59.686% 0.1009 0.1192); } ``` ```css .foo { color: #c65d07; color: color(display-p3 .724144 .386777 .148795); color: lab(52.2319% 40.1449 59.9171); } ``` -------------------------------- ### Exporting a Simple Visitor Plugin Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Define a visitor plugin by exporting an object with visitor methods. This example shows a plugin that exports a `FunctionExit` visitor to handle a `double` function. ```js // lightningcss-plugin-double-function export default { FunctionExit: { double(f) { // ... } } }; ``` -------------------------------- ### CSS Modules Example Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/index.html Illustrates the usage of CSS Modules for local scoping of class names and composition. It shows the input CSS with `composes` and the generated scoped class name and composition mapping. ```css .heading { composes: typography from './typography.css'; color: gray; } ``` ```css .EgL3uq_heading { color: gray; } ``` ```json { "heading": { "name": "EgL3uq_heading", "composes": [{ "type": "dependency", "name": "typography", "specifier": "./typography.css" }] } } ``` -------------------------------- ### Compiled CSS with Transition Property Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md The compiled CSS for the `transition` property example shows that only the unprefixed version remains, as it's supported by all target browsers. ```css .button { transition: background .2s; } ``` -------------------------------- ### CSS Variable Scoping Example Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Demonstrates how CSS variables are renamed when `dashedIdents` is enabled, and how `var()` references are updated to match the new local names. ```css :root { --accent-color: hotpink; } .button { background: var(--accent-color); } ``` ```css :root { --EgL3uq_accent-color: hotpink; } .EgL3uq_button { background: var(--EgL3uq_accent-color); } ``` -------------------------------- ### Plugin Package JSON Configuration Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Configure a plugin's package.json to include a descriptive name starting with `lightningcss-plugin-` and the `lightningcss-plugin` keyword for discoverability on npm. ```json { "name": "lightningcss-plugin-double-function", "keywords": ["lightningcss-plugin"], "main": "plugin.mjs" } ``` -------------------------------- ### Handle Unknown At-Rules with Visitors Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Process unknown at-rules by storing them as raw tokens in the AST. This example demonstrates declaring static variables using named at-rules and inlining them when an `@keyword` token is encountered. ```javascript let declared = new Map(); let res = transform({ filename: 'test.css', minify: true, code: Buffer.from(` @blue #056ef0; .menu_link { background: @blue; } `), visitor: { Rule: { unknown(rule) { declared.set(rule.name, rule.prelude); return []; } }, Token: { 'at-keyword'(token) { return declared.get(token.value); } } } }); assert.equal(res.code.toString(), '.menu_link{background:#056ef0}'); ``` -------------------------------- ### Add Vendor Prefix Before Overflow Property Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md This example shows how to use a `Property` visitor with a specific key (`overflow`) to insert a vendor-prefixed property (`-webkit-overflow-scrolling: touch`) before the original `overflow` property. This technique optimizes performance by only invoking the visitor when the target property is encountered. ```javascript let res = transform({ filename: 'test.css', minify: true, code: Buffer.from(` .foo { overflow: auto; } `), visitor: { Property: { overflow(property) { return [{ property: 'custom', value: { name: '-webkit-overflow-scrolling', value: [{ type: 'token', value: { type: 'ident', value: 'touch' } }] } }, property]; }, } } }); assert.equal(res.code.toString(), '.foo{-webkit-overflow-scrolling:touch;overflow:auto}'); ``` -------------------------------- ### Define and Use Custom At-Rules Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Interpret custom at-rule bodies as standard CSS declaration lists or rule lists using the `customAtRules` option. This example defines `@mixin` for reusable style blocks and `@apply` to inline them. ```javascript let mixins = new Map(); let res = transform({ filename: 'test.css', minify: true, targets: { chrome: 100 << 16 }, code: Buffer.from(` @mixin color { color: red; &.bar { color: yellow; } } .foo { @apply color; } `), customAtRules: { mixin: { prelude: '', body: 'style-block' }, apply: { prelude: '' } }, visitor: { Rule: { custom: { mixin(rule) { mixins.set(rule.prelude.value, rule.body.value); return []; }, apply(rule) { return mixins.get(rule.prelude.value); } } } } }); assert.equal(res.code.toString(), '.foo{color:red}.foo.bar{color:#ff0}'); ``` -------------------------------- ### Rust Background Struct Example Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/index.html This Rust code demonstrates the structure of a Background object, including its image, color, position, repeat, and size properties. It is used internally by Lightning CSS for representing CSS background properties. ```rust Background([Background { image: Url(Url { url: "img.png" }), color: CssColor(RGBA(RGBA { red: 0, green: 0, blue: 0, alpha: 0 })), position: Position { x: Length(Dimension(Px(20.0))), y: Length(Dimension(Px(10.0))), }, repeat: BackgroundRepeat { x: Repeat, y: Repeat, }, size: Explicit { width: LengthPercentage(Dimension(Px(50.0))), height: LengthPercentage(Dimension(Px(100.0))), }, attachment: Scroll, origin: PaddingBox, clip: BorderBox, }]) ``` -------------------------------- ### Manual Browser Target Specification Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Manually define browser targets using an object that maps browser names to minimum versions. This example targets Safari 13.2.0. ```javascript let targets = { safari: (13 << 16) | (2 << 8) }; ``` -------------------------------- ### Reduce CSS Transform Functions Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md This example shows how Lightning CSS reduces CSS transform functions to shorter equivalents, such as converting `translate(0, 50px)` to `translateY(50px)`. ```css .foo { transform: translate(0, 50px); } ``` ```css .foo{transform:translateY(50px)} ``` -------------------------------- ### Convert Matrix3d to Shorter Transforms Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md Lightning CSS converts `matrix()` and `matrix3d()` functions to their equivalent, shorter transform functions when possible. This example converts a `matrix3d` to `translate3d` and `rotateX`. ```css .foo { transform: matrix3d(1, 0, 0, 0, 0, 0.707106, 0.707106, 0, 0, -0.707106, 0.707106, 0, 100, 100, 10, 1); } ``` ```css .foo{transform:translate3d(100px,100px,10px)rotateX(45deg)} ``` -------------------------------- ### Convert Transforms to Matrix Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md When a single matrix would be shorter, Lightning CSS converts individual transform functions into a single `matrix()` function. This example combines multiple transforms into one matrix. ```css .foo { transform: translate(100px, 200px) rotate(45deg) skew(10deg) scale(2); } ``` ```css .foo{transform:matrix(1.41421,1.41421,-1.16485,1.66358,100,200)} ``` -------------------------------- ### Display Lightning CSS CLI Help Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Command to display all available options for the lightningcss CLI. ```shell npx lightningcss-cli --help ``` -------------------------------- ### Run Tests Source: https://github.com/parcel-bundler/lightningcss/blob/master/CONTRIBUTING.md Execute the test suite for the project. This includes both JavaScript and Rust tests. ```shell yarn test # js tests cargo test # rust tests ``` -------------------------------- ### Normalize Background Property Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md Lightning CSS normalizes CSS properties by filling in defaults and omitting them during minification. This example shows the background property being simplified. ```css .foo { background: 0% 0% / auto repeat scroll padding-box border-box red; } ``` ```css .foo{background:red} ``` -------------------------------- ### CLI Targets Configuration Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Configure browser targets using the `--targets` option with a browserslist query in the CLI. Alternatively, use `--browserslist` to load configuration from a file. ```ini # Defaults, applied when no other section matches the provided environment. firefox ESR # Targets applied only to the staging environment. [staging] samsung >= 4 ``` -------------------------------- ### Exporting an Options-Aware Visitor Plugin Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Create a visitor plugin that accepts options by exporting a function that returns the visitor object. This allows for configurable plugin behavior. ```js // lightningcss-plugin-env export default (values) => ({ EnvironmentVariable(env) { return values[env.name]; } }); ``` -------------------------------- ### Basic HTML and Body Styling Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Sets up basic styling for html and body elements, including margin, height, box-sizing, font family, color scheme, and background. ```css html, body { margin: 0; height: 100%; box-sizing: border-box; font-family: -apple-system, system-ui; color-scheme: dark; background: #111; } ``` -------------------------------- ### Run CSS Minification Benchmarks Source: https://github.com/parcel-bundler/lightningcss/blob/master/README.md Execute benchmark tests for CSS minification using different tools. This command runs the benchmark script with a specific CSS file as input. ```bash $ node bench.js bootstrap-4.css ``` ```bash $ node bench.js animate.css ``` ```bash $ node bench.js tailwind.css ``` -------------------------------- ### Build Core Package Source: https://github.com/parcel-bundler/lightningcss/blob/master/CONTRIBUTING.md Build the core package of the Lightning CSS project. This is a prerequisite for running tests. ```shell yarn build ``` -------------------------------- ### Build Project Variants Source: https://github.com/parcel-bundler/lightningcss/blob/master/CONTRIBUTING.md Build different variants of the project, including a production release build and the WebAssembly (WASM) target. ```shell yarn build yarn build-release yarn wasm:build yarn wasm:build-release ``` -------------------------------- ### Compose Visitors for AST Traversal Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Combine multiple visitor objects into a single visitor using `composeVisitors`. This allows for modularity and reuse of visitors across projects. The AST is traversed in a single pass, executing functions from each visitor. ```javascript import { transform, composeVisitors } from 'lightningcss'; let environmentVisitor = { EnvironmentVariable: { '--branding-padding': () => ({ type: 'length', value: { unit: 'px', value: 20 } }) } }; let doubleFunctionVisitor = { FunctionExit: { double(f) { if (f.arguments[0].type === 'length') { return { type: 'length', value: { unit: f.arguments[0].value.unit, value: f.arguments[0].value.value * 2 } }; } } } }; let res = transform({ filename: 'test.css', minify: true, code: Buffer.from(` .foo { padding: double(env(--branding-padding)); } `), visitor: composeVisitors([environmentVisitor, doubleFunctionVisitor]) }); assert.equal(res.code.toString(), '.foo{padding:40px}'); ``` -------------------------------- ### Vendor Prefixing for image-set() Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Lightning CSS automatically adds vendor-prefixed fallbacks for CSS features not supported by target browsers. For example, it adds `-webkit-image-set()` when `image-set()` is used and the target browser doesn't support the unprefixed version. ```css .logo { background: image-set(url(logo.png) 2x, url(logo.png) 1x); } ``` -------------------------------- ### Add File and Glob Dependencies with Visitors Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Use a function visitor to access `addDependency` for declaring file or glob dependencies. File dependencies trigger re-runs when the specified file changes, while glob dependencies trigger when any file matching the glob changes. This is crucial for cache invalidation and re-running transformations. ```js let res = transform({ filename: 'test.css', code: Buffer.from(` @dep "foo.js"; @glob "**/*.json"; .foo { width: 32px; } `), visitor: ({addDependency}) => ({ Rule: { unknown: { dep(rule) { let file = rule.prelude[0].value.value; addDependency({ type: 'file', filePath: file }); return []; }, glob(rule) { let glob = rule.prelude[0].value.value; addDependency({ type: 'glob', glob }); return []; } } } }) }); assert.equal(res.dependencies, [ { type: 'file', filePath: 'foo.js' }, { type: 'glob', filePath: '**/*.json' } ]); ``` -------------------------------- ### Implement Custom Resolver for bundleAsync Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/bundling.md Provide custom JavaScript functions for resolving @import specifiers and reading files. The read and resolve functions can return strings synchronously or Promises asynchronously. Use this to handle external URLs or custom file paths. ```javascript import { bundleAsync } from 'lightningcss'; let { code, map } = await bundleAsync({ filename: 'style.css', minify: true, resolver: { read(filePath) { return fs.readFileSync(filePath, 'utf8'); }, resolve(specifier, from) { if (/^https?:/.test(specifier)) { return {external: specifier}; } return path.resolve(path.dirname(from), specifier); } } }); ``` -------------------------------- ### Compile :lang() with multiple arguments to :is() Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md When :lang() has multiple arguments and :is() is unsupported, it is compiled using :is() with individual :lang() selectors. ```css a:lang(en, fr) { color:red } ``` ```css a:is(:lang(en), :lang(fr)) { color: red; } ``` -------------------------------- ### Bundle CSS with Lightning CSS API Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/bundling.md Use the `bundle` function from the `lightningcss` API to bundle CSS files. This function requires filesystem access and the `filename` option to specify the entry point. It returns the bundled code and a source map. ```javascript import { bundle } from 'lightningcss'; let { code, map } = bundle({ filename: 'style.css', minify: true }); ``` -------------------------------- ### Configure Vite with Lightning CSS Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Configure Vite to use Lightning CSS as its CSS transformer and minifier, including setting browser targets. ```javascript import browserslist from 'browserslist'; import {browserslistToTargets} from 'lightningcss'; export default { css: { transformer: 'lightningcss', lightningcss: { targets: browserslistToTargets(browserslist('>= 0.25%')) } }, build: { cssMinify: 'lightningcss' } }; ``` -------------------------------- ### Reference CSS Variables from Other Files Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Use the `from` keyword to reference CSS variables defined in other CSS modules files. Ensure the path is correct. ```css .button { background: var(--accent-color from './vars.module.css'); } ``` -------------------------------- ### Define Browser Targets with Browserslist Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Use the `browserslist` library to generate a targets object for Lightning CSS. Call `browserslist` once per build and reuse the `targets` object for optimal performance. ```javascript import browserslist from 'browserslist'; import { transform, browserslistToTargets } from 'lightningcss'; // Call this once per build. let targets = browserslistToTargets(browserslist('>= 0.25%')); // Use `targets` for each file you transform. let { code, map } = transform({ // ... targets }); ``` -------------------------------- ### Label Display Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Sets labels to display as block elements. ```css label { display: block; } ``` -------------------------------- ### Compile system-ui font to fallback stack Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Lightning CSS automatically compiles `system-ui` font-family to a cross-platform compatible stack when unsupported. ```css .foo { font-family: system-ui; } ``` ```css .foo { font-family: system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Noto Sans, Ubuntu, Cantarell, Helvetica Neue; } ``` -------------------------------- ### Transform CSS with Lightning CSS Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Use the transform API to minify CSS and generate source maps. Requires importing the transform function. ```javascript import { transform } from 'lightningcss'; let { code, map } = transform({ filename: 'style.css', code: Buffer.from('.foo { color: red }'), minify: true, sourceMap: true }); ``` -------------------------------- ### Compile Media Query Ranges Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Media query range syntax is compiled to min/max media features for compatibility with browsers that do not support the range syntax. ```css @media (480px <= width <= 768px) { .foo { color: red } } ``` ```css @media (min-width: 480px) and (max-width: 768px) { .foo { color: red } } ``` -------------------------------- ### Global Exceptions Compiled Output Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md The compiled output demonstrates how `:global` selectors are treated differently, preserving their original names while other selectors are hashed. ```css .EgL3uq_foo .bar { color: red; } .EgL3uq_foo .EgL3uq_bar { color: #ff0; } ``` -------------------------------- ### Configure Lightning CSS in Parcel Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Configure Lightning CSS options like CSS modules, drafts, and pseudo-classes within the Parcel configuration in package.json. ```json { "@parcel/transformer-css": { "cssModules": true, "drafts": { "nesting": true, "customMedia": true }, "pseudoClasses": { "focusVisible": "focus-ring" } } } ``` -------------------------------- ### Enable CSS Modules Transformation Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Use the `cssModules: true` option in the `transform` API to enable CSS Modules. This generates hashed class names and an exports object mapping original names to hashed names. ```javascript import {transform} from 'lightningcss'; let {code, map, exports} = transform({ // ... cssModules: true, code: Buffer.from(` .logo { background: skyblue; } `), }); ``` -------------------------------- ### Enable custom media queries in Lightning CSS Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Enable the `customMedia` option to compile custom media queries, which are part of the Media Queries Level 5 draft spec. ```javascript let { code, map } = transform({ // ... drafts: { customMedia: true } }); ``` ```css @custom-media --modern (color), (hover); @media (--modern) and (width > 1024px) { .a { color: green; } } ``` ```css @media ((color) or (hover)) and (width > 1024px) { .a { color: green; } } ``` -------------------------------- ### Compile :dir() to :lang() Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md The :dir() selector is compiled to :lang() for browsers that do not support :dir(). ```css a:dir(rtl) { color:red } ``` ```css a:lang(ae, ar, arc, bcc, bqi, ckb, dv, fa, glk, he, ku, mzn, nqo, pnb, ps, sd, ug, ur, yi) { color: red; } ``` -------------------------------- ### Global Exceptions for Selectors Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Use the `:global` pseudo-class to opt out of CSS Modules hashing for specific selectors within a CSS module. ```css .foo :global(.bar) { color: red; } .foo .bar { color: green; } ``` -------------------------------- ### Multiple Local Class Composition Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Multiple local classes can be composed by separating them with spaces in the `composes` property. ```css .logo { composes: bg-indigo padding-large; } ``` -------------------------------- ### Header Link Styling Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Ensures header links inherit their color and styles the GitHub icon. ```css header a { color: inherit; } header .github { fill: currentColor; } ``` -------------------------------- ### Configure Custom Naming Pattern for CSS Modules Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Set a custom `pattern` for generating scoped class names and identifiers. This allows for prefixes and custom naming conventions. ```javascript let {code, map, exports} = transform({ // ... cssModules: { pattern: 'my-company-[name]-[hash]-[local]', }, }); ``` -------------------------------- ### Evaluating color-mix() Function Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Demonstrates the `color-mix()` function, which Lightning CSS evaluates statically if all color components are known, producing a static color value. ```css .foo { color: color-mix(in hsl, hsl(120deg 10% 20%) 25%, hsl(30deg 30% 40%)); } ``` -------------------------------- ### Compiled image-set() with Webkit Fallback Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md The compiled output for `image-set()` includes a `-webkit-` prefixed version as a fallback, ensuring compatibility with older Webkit browsers. ```css .logo { background: -webkit-image-set(url(logo.png) 2x, url(logo.png) 1x); background: image-set("logo.png" 2x, "logo.png"); } ``` -------------------------------- ### Enable Scoping for Animations, Grid, and Custom Identifiers Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Set `animation: true`, `grid: true`, and `customIdents: true` to enable scoping for these features, which are scoped by default. ```javascript let {code, map, exports} = transform({ // ... cssModules: { animation: true, grid: true, customIdents: true, }, }); ``` -------------------------------- ### Inline CSS with @import Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/bundling.md Use the `@import` at-rule in CSS to inline another CSS file into the same bundle. Referenced files should be relative to the containing CSS file. `@import` rules must appear before all other rules except `@charset` and `@layer`. ```css @import 'other.css'; ``` -------------------------------- ### Nesting CSS Rules Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Demonstrates the use of nested style rules, a feature compiled by Lightning CSS into standard, un-nested rules compatible with all browsers. ```css .foo { color: blue; .bar { color: red; } } ``` -------------------------------- ### Compiled Modules and Dependencies Grid Area and Expansion Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Assigns grid areas for 'compiledModules' and 'compiledDependencies' and defines their expanded state behavior. ```css #compiledModules { grid-area: compiledModules; overflow: hidden; } #compiledDependencies { grid-area: compiledDependencies; overflow: hidden; } #compiledModules[data-expanded=true], #compiledDependencies[data-expanded=true] { grid-row: compiledModules-start; grid-column: compiledModules-start / compiledDependencies-end; } ``` -------------------------------- ### Dependency Class Composition Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Reference class names from other CSS files using `composes` with the `from` keyword. The `exports` object will indicate the dependency. ```css .logo { composes: bg-indigo from './colors.module.css'; } ``` -------------------------------- ### CSS Grid Pattern Configuration Note Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md When using CSS grid, the `pattern` must end with `[local]` to ensure correct referencing of auto-generated grid line names like `-start` and `-end`. ```javascript let { code, map, exports } = transform({ // ... cssModules: { // ❌ [local] must be at the end so that // auto-generated grid line names work pattern: '[local]-[hash]' // ✅ do this instead pattern: '[hash]-[local]' } }); ``` -------------------------------- ### Reference Global CSS Variables Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Use `from global` to reference CSS variables that are intended to be global and not scoped to any specific module. ```css .button { color: var(--color from global); } ``` -------------------------------- ### Returning Raw CSS Values from Lightning CSS Visitors Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Simplify transformations by returning a `raw` string property from visitors that yield declarations or tokens. Lightning CSS will automatically parse this string into the AST, as demonstrated with a custom `color` function returning a raw `rgb` value. ```js let res = transform({ minify: true, code: Buffer.from(` .foo { color: color('red'); } `), visitor: { Function: { color() { return { raw: 'rgb(255, 0, 0)' }; } } } }); assert.equal(res.code.toString(), '.foo{color:red}'); ``` -------------------------------- ### Implement light-dark() with CSS Variables Fallback Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Converts the light-dark() function to use CSS variables with fallbacks, controlled by the color-scheme property for theme support. ```css html { color-scheme: light dark; } html[data-theme=light] { color-scheme: light; } html[data-theme=dark] { color-scheme: dark; } button { background: light-dark(#aaa, #444); } ``` ```css html { --lightningcss-light: initial; --lightningcss-dark: ; color-scheme: light dark; } @media (prefers-color-scheme: dark) { html { --lightningcss-light: ; --lightningcss-dark: initial; } } html[data-theme="light"] { --lightningcss-light: initial; --lightningcss-dark: ; color-scheme: light; } html[data-theme="dark"] { --lightningcss-light: ; --lightningcss-dark: initial; color-scheme: dark; } button { background: var(--lightningcss-light, #aaa) var(--lightningcss-dark, #444); } ``` -------------------------------- ### Configure webpack to use Lightning CSS for Minification Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/docs.md Configure css-minimizer-webpack-plugin in your webpack.config.js to use Lightning CSS for CSS minification. Specify targets using browserslist. ```javascript // webpack.config.js const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const lightningcss = require('lightningcss'); const browserslist = require('browserslist'); module.exports = { optimization: { minimize: true, minimizer: [ new CssMinimizerPlugin({ minify: CssMinimizerPlugin.lightningCssMinify, minimizerOptions: { targets: lightningcss.browserslistToTargets(browserslist('>= 0.25%')) }, }), ], }, }; ``` -------------------------------- ### Enable non-standard deep selector combinator Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Enable the `deepSelectorCombinator` option under `nonStandard` to support Vue/Angular `>>>` and `/deep/` selector combinators. ```javascript let { code, map } = transform({ // ... nonStandard: { deepSelectorCombinator: true } }); ``` -------------------------------- ### Compile :is() with fallback to prefixed selectors Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md The :is() selector is compiled to -webkit-any and -moz-any prefixed selectors for older browser compatibility. Note: Prefixed selectors do not support complex selectors. ```css p:is(:first-child, .lead) { margin-top: 0; } ``` ```css p:-webkit-any(:first-child, .lead) { margin-top: 0; } ``` ```css p:-moz-any(:first-child, .lead) { margin-top: 0; } ``` ```css p:is(:first-child, .lead) { margin-top: 0; } ``` -------------------------------- ### Source Grid Area and Expansion Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Assigns the 'source' grid area and defines its expanded state behavior. ```css #source { grid-area: source; overflow: hidden; } #source[data-expanded=true] { grid-row: source-start / visitor-end; } ``` -------------------------------- ### Reduce calc() Expressions Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md Lightning CSS simplifies `calc()` expressions to constant values where possible, especially when units are consistent. Expressions involving CSS variables are not modified. ```css .foo { width: calc(100px * 2); height: calc(((75.37% - 63.5px) - 900px) + (2 * 100px)); } ``` ```css .foo{width:200px;height:calc(75.37% - 763.5px)} ``` -------------------------------- ### Transforming Custom Properties with Lightning CSS Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Handle custom properties like `size` by using the `custom` visitor within the `Property` visitor. This allows expanding a single custom property into multiple standard properties, such as `width` and `height`, based on its value type. ```js let res = transform({ minify: true, code: Buffer.from(` .foo { size: 12px; } `), visitor: { Property: { custom: { size(property) { // Handle the size property when the value is a length. if (property.value[0].type === 'length') { let value = { type: 'length-percentage', value: { type: 'dimension', value: property.value[0].value } }; return [ { property: 'width', value }, { property: 'height', value } ]; } } } } } }); assert.equal(res.code.toString(), '.foo{width:12px;height:12px}'); ``` -------------------------------- ### Convert Space-Separated Color Notation and Hex with Alpha Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Transforms space-separated color notation to hex and hex colors with alpha to rgba() for older browser support. ```css .foo { color: #7bffff80; background: rgb(123 255 255); } ``` ```css .foo { color: rgba(123, 255, 255, .5); background: #7bffff; } ``` -------------------------------- ### Replace pseudo classes with CSS classes Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Configure `pseudoClasses` to replace CSS pseudo classes like `:focus-visible` with specified CSS classes for polyfilling in older browsers. ```javascript let { code, map } = transform({ // ... pseudoClasses: { focusVisible: 'focus-visible' } }); ``` -------------------------------- ### Global Class Composition Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Compose global (non-hashed) classes using the `global` keyword in the `composes` property. ```css .search { composes: search-widget from global; } ``` -------------------------------- ### Header Styling Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Styles the header element for flex alignment and defines a custom property for gold color. ```css header { display: flex; align-items: center; margin-bottom: 5px; --gold: lch(80% 82.34 80.104); } ``` -------------------------------- ### Compile Logical Properties to Directional Fallbacks Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Transforms CSS logical properties into directional equivalents using the :dir() selector for compatibility. ```css .foo { border-start-start-radius: 20px } ``` ```css .foo:dir(ltr) { border-top-left-radius: 20px; } .foo:dir(rtl) { border-top-right-radius: 20px; } ``` -------------------------------- ### Using Exit Visitors for Post-Order Traversal in Lightning CSS Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transforms.md Employ `Exit` visitors (e.g., `FunctionExit`) to process nodes after their children have been visited, enabling post-order traversal. This is useful for operations that depend on the transformed state of child nodes, such as processing function arguments after environment variables within them have been resolved. ```js let res = transform({ filename: 'test.css', minify: true, code: Buffer.from(` .foo { padding: double(env(--branding-padding)); } `), visitor: { FunctionExit: { // This will run after the EnvironmentVariable visitor, below. double(f) { if (f.arguments[0].type === 'length') { return { type: 'length', value: { unit: f.arguments[0].value.unit, value: f.arguments[0].value.value * 2 } }; } } }, EnvironmentVariable: { // This will run before the FunctionExit visitor, above. '--branding-padding': () => ({ type: 'length', value: { unit: 'px', value: 20 } }) } } }); assert.equal(res.code.toString(), '.foo{padding:40px}'); ``` -------------------------------- ### Convert LAB Color to Fallback Values Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Converts LAB colors to RGB and display-p3 fallbacks for unsupported browsers. This preserves high color gamut colors. ```css .foo { color: lab(40% 56.6 39); } ``` ```css .foo { color: #b32323; color: color(display-p3 .643308 .192455 .167712); color: lab(40% 56.6 39); } ``` -------------------------------- ### Summary Font Weight Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Makes the font weight of summary elements bold. ```css summary { font-weight: bold; } ``` -------------------------------- ### Body Layout Styling Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Styles the body element for a flex column layout with specific gaps, padding, and margin for the header. ```css body { display: flex; flex-direction: column; gap: 5px; padding: 10px; } ``` -------------------------------- ### Main Layout Grid Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Defines the grid layout for the main content area, specifying grid areas, columns, rows, and gaps. ```css main { display: grid; grid-template-areas: "sidebar source compiled compiled" "sidebar visitor compiledModules compiledDependencies"; grid-template-columns: auto 2fr 1fr 1fr; grid-template-rows: 1fr 1fr; flex: 1; gap: 10px; overflow: hidden; } ``` -------------------------------- ### Convert HWB Color to RGB Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Converts HWB colors to their RGB equivalent for compatibility with browsers that do not support HWB. ```css .foo { color: hwb(194 0% 0%); } ``` ```css .foo { color: #00c4ff; } ``` -------------------------------- ### Minify CSS Colors Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md Colors are converted to their shortest valid format, such as hex notation, when possible without altering the color gamut. This includes converting `rgba()` and `hsl()` to hex, and precomputing color functions like `color-mix()` when components are known. ```css .foo { color: rgba(255, 255, 0, 0.8) } ``` ```css .foo{color:#ff0c} ``` ```css .foo { color: rgb(from rebeccapurple r calc(g * 2) b); background: color-mix(in hsl, hsl(120deg 10% 20%), hsl(30deg 30% 40%)); } ``` ```css .foo{color:#669;background:#545c3d} ``` -------------------------------- ### Enable Minification with Lightning CSS API Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/minification.md To enable minification when using the Lightning CSS API, set the `minify` option to `true` within the `transform` function. ```javascript import { transform } from 'lightningcss'; let { code, map } = transform({ // ... minify: true }); ``` -------------------------------- ### Logo Styling Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Styles the logo element within the header, including its positioning and stroke properties. ```css header .logo { grid-area: logo; place-self: center end; height: 60px; } header .logo .outer { stroke-width: 30px; stroke: var(--gold); } ``` -------------------------------- ### Heading 1 Styling Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/playground/index.html Styles the main heading (h1) with a specific font, size, letter spacing, and color. ```css header h1 { font-family: urbane-rounded, ui-rounded, system-ui; font-size: 35px; letter-spacing: -0.02em; color: var(--gold); padding: 20px 0; margin: 0 20px; flex: 1; } ``` -------------------------------- ### Nesting Conditional Rules like @media Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Shows how conditional rules like `@media` can be nested within style rules. Lightning CSS compiles this into a standard structure where the conditional rule applies to the parent selector. ```css .foo { display: grid; @media (orientation: landscape) { grid-auto-flow: column; } } ``` -------------------------------- ### Simplify CSS Math Functions Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Lightning CSS simplifies math functions like round(), sin(), and pi when all arguments are known, converting them to their computed values. ```css .foo { width: round(calc(100px * sin(pi / 4)), 5px); } ``` ```css .foo { width: 70px; } ``` -------------------------------- ### Local Class Composition Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/css-modules.md Use the `composes` property in CSS Modules to inherit styles from other local classes, enabling style mixins. The `exports` object reflects these compositions. ```css .bg-indigo { background: indigo; } .indigo-white { composes: bg-indigo; color: white; } ``` -------------------------------- ### Convert color() Function to RGB Fallback Source: https://github.com/parcel-bundler/lightningcss/blob/master/website/pages/transpilation.md Transforms the color() function, including predefined color spaces like a98-rgb, to RGB for older browser compatibility. ```css .foo { color: color(a98-rgb 0.44091 0.49971 0.37408); } ``` ```css .foo { color: #6a805d; color: color(a98-rgb .44091 .49971 .37408); } ```