Unverified Commit 187f35f2 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Add experimental.lightningCssFeatures config option (#90901)

### What?

Adds a new `experimental.lightningCssFeatures` config option that lets
users control which CSS features lightningcss should always transpile
(`include`) or never transpile (`exclude`), regardless of browserslist
targets.

```js
// next.config.js
module.exports = {
  experimental: {
    useLightningcss: true,
    lightningCssFeatures: {
      include: ['light-dark', 'oklab-colors'],
      exclude: ['nesting'],
    },
  },
}
```

### Why?

Currently, lightningcss feature transpilation is determined solely by
browserslist targets. There's no way to force transpilation of a
specific feature (e.g., `light-dark()`) when targeting modern browsers
that already support it, or to skip transpilation of a feature that the
user wants to preserve as-is.

This is useful for:
- Forcing polyfill-style transpilation for features with incomplete
browser support
- Testing transpiled output for specific features
- Opting out of specific transforms that may interfere with CSS tooling
downstream

### How?

**TypeScript config & validation:**
- `config-shared.ts`: `LIGHTNINGCSS_FEATURE_NAMES` const array (single
source of truth) with `LightningCssFeature` type derived from it, and
`LightningCssFeatures` interface
- `config-schema.ts`: Zod validation using
`z.enum(LIGHTNINGCSS_FEATURE_NAMES)` for both include/exclude arrays

**Feature name → bitmask mapping (Rust, shared via NAPI):**
- `crates/next-core/src/next_config.rs`:
`lightningcss_feature_names_to_mask()` maps feature name strings to
`lightningcss::targets::Features` bitflag constants and returns a
`Result<u32>` bitmask. Unknown feature names produce an error via
`bail!`.
- Exposed to JS via NAPI as `lightningcssFeatureNamesToMaskNapi`,
callable through `bindings.css.lightning.featureNamesToMask(names)`
- Single source of truth for feature name resolution — both webpack and
Turbopack paths use this Rust function

**Webpack path:**
- `global.ts` / `modules.ts` pass config through to loader options
- `loader.ts` calls `featureNamesToMask()` via the native bindings to
compute include/exclude masks, then passes them to the SWC `transform()`
call
- The `lightningCssFeatures` without `useLightningcss` warning only
shows when using webpack (Turbopack always uses lightningcss)

**Turbopack path (Rust):**
- `next_config.rs`: `LightningCssFeatures` struct for deserialization,
accessor methods converting names → u32 bitmask via
`lightningcss_feature_names_to_mask()`
- Config flows through `CssOptionsContext` → `ModuleType::Css` →
`CssModuleAsset` (using `LightningCssFeatureFlags { include, exclude }`
struct) → `process.rs` where bitmasks are merged into
`lightningcss::targets::Targets { include, exclude }`
- Uses `u32` bitmask representation throughout to avoid adding
lightningcss dependency to non-CSS crates

**Defaults preserved:** `Nesting | MediaRangeSyntax` for Turbopack,
`Nesting` for Webpack. User `include` is OR-ed on top, user `exclude`
masks bits off.

**Feature names:** 21 individual features (bit 0–20) + 3 composite
groups (`selectors`, `media-queries`, `colors`), all in dash-case.

### Test

- **Include test**
(`test/e2e/app-dir/experimental-lightningcss-features/`) — targets
Chrome 123 (which natively supports `light-dark()`) with `include:
['light-dark']`, then asserts the CSS output contains lightningcss
transpilation markers (`--lightningcss-light`, `--lightningcss-dark`)
instead of raw `light-dark()`.
- **Exclude test**
(`test/e2e/app-dir/experimental-lightningcss-features-exclude/`) —
targets Chrome 100 (which does NOT support `light-dark()` natively) with
`exclude: ['light-dark']`, then asserts the CSS output preserves raw
`light-dark()` calls and does not contain transpilation markers.
parent ff36c17c
......@@ -4542,6 +4542,7 @@ dependencies = [
"indexmap 2.13.0",
"indoc",
"itertools 0.10.5",
"lightningcss",
"mime_guess",
"modularize_imports",
"next-custom-transforms",
......@@ -4636,6 +4637,7 @@ dependencies = [
"futures-util",
"getrandom 0.2.15",
"iana-time-zone",
"lightningcss",
"lightningcss-napi",
"mdxjs",
"napi",
......
......@@ -22,6 +22,7 @@ futures = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }
indoc = { workspace = true }
itertools = { workspace = true }
lightningcss = { workspace = true }
mime_guess = "2.0.4"
once_cell = { workspace = true }
percent-encoding = "2.3.1"
......
......@@ -343,6 +343,7 @@ pub async fn get_client_module_options_context(
css: CssOptionsContext {
source_maps,
module_css_condition: Some(module_styles_rule_condition()),
lightningcss_features: *next_config.lightningcss_feature_flags().await?,
..Default::default()
},
static_url_tag: Some(rcstr!("client")),
......
......@@ -1188,6 +1188,7 @@ pub struct ExperimentalConfig {
// Use project.is_persistent_caching() instead
// turbopack_file_system_cache_for_dev: Option<bool>,
// turbopack_file_system_cache_for_build: Option<bool>,
lightning_css_features: Option<LightningCssFeatures>,
}
#[derive(
......@@ -1207,6 +1208,25 @@ pub struct SubResourceIntegrity {
pub algorithm: Option<RcStr>,
}
#[derive(
Clone,
Debug,
Default,
PartialEq,
Eq,
Deserialize,
TraceRawVcs,
NonLocalValue,
OperationValue,
Encode,
Decode,
)]
#[serde(rename_all = "camelCase")]
pub struct LightningCssFeatures {
pub include: Option<Vec<RcStr>>,
pub exclude: Option<Vec<RcStr>>,
}
#[derive(
Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode,
)]
......@@ -2130,6 +2150,23 @@ impl NextConfig {
)
}
#[turbo_tasks::function]
pub fn lightningcss_feature_flags(
&self,
) -> Result<Vc<turbopack_css::LightningCssFeatureFlags>> {
Ok(turbopack_css::LightningCssFeatureFlags {
include: lightningcss_features_field_mask(
&self.experimental.lightning_css_features,
|f| f.include.as_ref(),
)?,
exclude: lightningcss_features_field_mask(
&self.experimental.lightning_css_features,
|f| f.exclude.as_ref(),
)?,
}
.cell())
}
#[turbo_tasks::function]
pub async fn client_source_maps(&self, mode: Vc<NextMode>) -> Result<Vc<SourceMapsType>> {
let input_source_maps = self
......@@ -2289,6 +2326,65 @@ impl JsConfig {
}
}
/// Extract either the `include` or `exclude` field from `LightningCssFeatures`
/// and convert the feature names to a bitmask.
fn lightningcss_features_field_mask(
features: &Option<LightningCssFeatures>,
field: impl FnOnce(&LightningCssFeatures) -> Option<&Vec<RcStr>>,
) -> Result<u32> {
features
.as_ref()
.and_then(field)
.map(|names| lightningcss_feature_names_to_mask(names))
.unwrap_or(Ok(0))
}
/// Convert dash-case feature name strings to a lightningcss `Features` bitmask.
///
/// Uses the canonical `Features` constants from the lightningcss crate.
/// Composite names (`selectors`, `media-queries`, `colors`) OR together the
/// bits of their constituent individual features.
///
/// Feature names must match: `packages/next/src/server/config-shared.ts`
/// (`LIGHTNINGCSS_FEATURE_NAMES`)
pub fn lightningcss_feature_names_to_mask(
names: &[impl std::ops::Deref<Target = str>],
) -> Result<u32> {
use lightningcss::targets::Features;
let mut mask = Features::empty();
for name in names {
mask |= match &**name {
"nesting" => Features::Nesting,
"not-selector-list" => Features::NotSelectorList,
"dir-selector" => Features::DirSelector,
"lang-selector-list" => Features::LangSelectorList,
"is-selector" => Features::IsSelector,
"text-decoration-thickness-percent" => Features::TextDecorationThicknessPercent,
"media-interval-syntax" => Features::MediaIntervalSyntax,
"media-range-syntax" => Features::MediaRangeSyntax,
"custom-media-queries" => Features::CustomMediaQueries,
"clamp-function" => Features::ClampFunction,
"color-function" => Features::ColorFunction,
"oklab-colors" => Features::OklabColors,
"lab-colors" => Features::LabColors,
"p3-colors" => Features::P3Colors,
"hex-alpha-colors" => Features::HexAlphaColors,
"space-separated-color-notation" => Features::SpaceSeparatedColorNotation,
"font-family-system-ui" => Features::FontFamilySystemUi,
"double-position-gradients" => Features::DoublePositionGradients,
"vendor-prefixes" => Features::VendorPrefixes,
"logical-properties" => Features::LogicalProperties,
"light-dark" => Features::LightDark,
// Composite groups
"selectors" => Features::Selectors,
"media-queries" => Features::MediaQueries,
"colors" => Features::Colors,
_ => bail!("Unknown lightningcss feature: {}", &**name),
};
}
Ok(mask.bits())
}
#[cfg(test)]
mod tests {
use super::*;
......
......@@ -571,6 +571,7 @@ pub async fn get_server_module_options_context(
css: CssOptionsContext {
source_maps,
module_css_condition: Some(module_styles_rule_condition()),
lightningcss_features: *next_config.lightningcss_feature_flags().await?,
..Default::default()
},
tree_shaking_mode: tree_shaking_mode_for_user_code,
......
......@@ -107,6 +107,7 @@ swc_core = { workspace = true, features = [
# Dependencies for the native, non-wasm32 build.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
lightningcss-napi = { workspace = true }
lightningcss = { workspace = true }
tokio = { workspace = true, features = ["full"] }
turbo-rcstr = { workspace = true, features = ["napi"] }
turbo-tasks = { workspace = true }
......
use napi::{CallContext, JsObject, JsUnknown};
use napi_derive::{js_function, module_exports};
use napi_derive::{js_function, module_exports, napi};
use next_core::next_config::lightningcss_feature_names_to_mask;
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[js_function(1)]
......@@ -13,6 +14,16 @@ fn transform_style_attribute(ctx: CallContext) -> napi::Result<JsUnknown> {
lightningcss_napi::transform_style_attribute(ctx)
}
/// Convert an array of dash-case feature name strings to a lightningcss
/// `Features` bitmask (u32). Called from the webpack lightningcss-loader to
/// avoid duplicating the name-to-bit mapping in JavaScript.
#[napi]
#[allow(dead_code)]
fn lightningcss_feature_names_to_mask_napi(names: Vec<String>) -> napi::Result<u32> {
lightningcss_feature_names_to_mask(&names)
.map_err(|e| napi::Error::from_reason(format!("{}", e)))
}
#[cfg_attr(not(target_arch = "wasm32"), module_exports)]
fn init(mut exports: JsObject) -> napi::Result<()> {
exports.create_named_method("lightningCssTransform", transform)?;
......
......@@ -33,9 +33,94 @@ const nextConfig = {
module.exports = nextConfig
```
## `lightningCssFeatures`
By default, Lightning CSS decides which CSS features to transpile based on your [browserslist](https://browsersl.ist/) targets. The `lightningCssFeatures` option lets you override this by forcing specific features to always be transpiled (`include`) or never be transpiled (`exclude`), regardless of browser support.
This applies to both webpack (when `useLightningcss` is enabled) and Turbopack.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useLightningcss: true,
lightningCssFeatures: {
// Always transpile these features, even if targets support them
include: ['light-dark', 'oklab-colors'],
// Never transpile these features, even if targets don't support them
exclude: ['nesting'],
},
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useLightningcss: true,
lightningCssFeatures: {
// Always transpile these features, even if targets support them
include: ['light-dark', 'oklab-colors'],
// Never transpile these features, even if targets don't support them
exclude: ['nesting'],
},
},
}
module.exports = nextConfig
```
### Options
| Option | Type | Description |
| --------- | ---------- | -------------------------------------------------------------------------- |
| `include` | `string[]` | Features to always transpile, regardless of browser targets. |
| `exclude` | `string[]` | Features to never transpile, even when browser targets would require them. |
### Available features
Individual features:
| Feature name | Description |
| ----------------------------------- | ---------------------------------------------------- |
| `nesting` | [CSS Nesting](https://drafts.csswg.org/css-nesting/) |
| `not-selector-list` | `:not` with multiple selectors |
| `dir-selector` | `:dir()` selector |
| `lang-selector-list` | `:lang()` with multiple languages |
| `is-selector` | `:is()` selector |
| `text-decoration-thickness-percent` | Percentage values in `text-decoration-thickness` |
| `media-interval-syntax` | Media query range interval syntax |
| `media-range-syntax` | Media query range syntax (`width >= 600px`) |
| `custom-media-queries` | `@custom-media` rules |
| `clamp-function` | `clamp()` function |
| `color-function` | `color()` function |
| `oklab-colors` | `oklab()` and `oklch()` colors |
| `lab-colors` | `lab()` and `lch()` colors |
| `p3-colors` | Display P3 colors |
| `hex-alpha-colors` | 4 and 8 digit hex colors with alpha |
| `space-separated-color-notation` | Space-separated color notation (`rgb(0 0 0)`) |
| `font-family-system-ui` | `system-ui` font family |
| `double-position-gradients` | Double-position gradient stops |
| `vendor-prefixes` | Vendor-prefixed properties and values |
| `logical-properties` | Logical properties and values |
| `light-dark` | `light-dark()` color function |
Composite groups (shorthand for enabling multiple features at once):
| Group name | Includes |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `selectors` | `nesting`, `not-selector-list`, `dir-selector`, `lang-selector-list`, `is-selector` |
| `media-queries` | `media-interval-syntax`, `media-range-syntax`, `custom-media-queries` |
| `colors` | `color-function`, `oklab-colors`, `lab-colors`, `p3-colors`, `hex-alpha-colors`, `space-separated-color-notation`, `light-dark` |
## Version History
| Version | Changes |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `16.2.0` | `lightningCssFeatures` added. |
| `15.1.0` | Support for `useSwcCss` was removed from Turbopack. |
| `14.2.0` | Turbopack's default CSS processor was changed from `@swc/css` to Lightning CSS. `useLightningcss` became ignored on Turbopack, and a legacy `experimental.turbo.useSwcCss` option was added. |
......@@ -1087,5 +1087,6 @@
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport",
"1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body",
"1089": "\\`experimental.cachedNavigations\\` requires \\`cacheComponents\\` to be enabled. Please update your %s accordingly."
"1089": "\\`experimental.cachedNavigations\\` requires \\`cacheComponents\\` to be enabled. Please update your %s accordingly.",
"1090": "`css.lightning.featureNamesToMask` is not supported by the wasm bindings."
}
......@@ -18,6 +18,7 @@ export function lightningCssTransform(args: object): Promise<unknown>
export function lightningCssTransformStyleAttribute(
args: object
): Promise<unknown>
export function lightningcssFeatureNamesToMaskNapi(names: Array<string>): number
// GENERATED-TYPES-BELOW
// DO NOT MANUALLY EDIT THESE TYPES
......
......@@ -1346,6 +1346,11 @@ async function loadWasm(importPath = '') {
'`css.lightning.transformStyleAttr` is not supported by the wasm bindings.'
)
},
featureNamesToMask: function (_names: string[]) {
throw new Error(
'`css.lightning.featureNamesToMask` is not supported by the wasm bindings.'
)
},
},
},
isWasm: true,
......@@ -1651,6 +1656,9 @@ function loadNative(importPath?: string): Binding {
transformAttrOptions
)
},
featureNamesToMask(names: string[]) {
return bindings.lightningcssFeatureNamesToMaskNapi(names)
},
},
},
reactCompiler: {
......
......@@ -52,6 +52,7 @@ export interface Binding {
lightning: {
transform(transformOptions: any): Promise<any>
transformStyleAttr(transformAttrOptions: any): Promise<any>
featureNamesToMask(names: string[]): number
}
}
......
......@@ -37,6 +37,7 @@ export function getGlobalCssLoader(
modules: false,
targets: ctx.supportedBrowsers,
postcss,
lightningCssFeatures: ctx.experimental.lightningCssFeatures,
},
})
} else {
......
......@@ -42,6 +42,7 @@ export function getCssModuleLoader(
},
targets: ctx.supportedBrowsers,
postcss,
lightningCssFeatures: ctx.experimental.lightningCssFeatures,
},
})
} else {
......
......@@ -357,6 +357,18 @@ export async function LightningCssLoader(
...icssVisitor,
}
// Compute feature include/exclude masks from user config.
// Default: always transpile nesting (bit 0). User `include` adds flags,
// user `exclude` removes them from both include and exclude masks.
const featureNamesToMask = getBindingsSync().css.lightning.featureNamesToMask
const userIncludeMask = options.lightningCssFeatures?.include
? featureNamesToMask(options.lightningCssFeatures.include)
: 0
const userExcludeMask = options.lightningCssFeatures?.exclude
? featureNamesToMask(options.lightningCssFeatures.exclude)
: 0
const includeMask = (1 | userIncludeMask) & ~userExcludeMask // 1 = Features.Nesting
try {
const {
code,
......@@ -378,7 +390,8 @@ export async function LightningCssLoader(
targets: getTargets({ targets: userTargets, key: ECacheKey.loader }),
inputSourceMap:
this.sourceMap && prevMap ? JSON.stringify(prevMap) : undefined,
include: 1, // Features.Nesting
include: includeMask,
exclude: userExcludeMask,
})
let cssCodeAsString = code.toString()
......
......@@ -5,14 +5,15 @@ import { z } from 'next/dist/compiled/zod'
import type zod from 'next/dist/compiled/zod'
import type { SizeLimit } from '../types'
import type {
ExportPathMap,
TurbopackLoaderItem,
TurbopackOptions,
TurbopackRuleConfigItem,
TurbopackRuleConfigCollection,
TurbopackRuleCondition,
TurbopackLoaderBuiltinCondition,
import {
LIGHTNINGCSS_FEATURE_NAMES,
type ExportPathMap,
type TurbopackLoaderItem,
type TurbopackOptions,
type TurbopackRuleConfigItem,
type TurbopackRuleConfigCollection,
type TurbopackRuleCondition,
type TurbopackLoaderBuiltinCondition,
} from './config-shared'
import type {
Header,
......@@ -355,6 +356,12 @@ export const experimentalSchema = {
serverSourceMaps: z.boolean().optional(),
useWasmBinary: z.boolean().optional(),
useLightningcss: z.boolean().optional(),
lightningCssFeatures: z
.object({
include: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),
exclude: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),
})
.optional(),
testProxy: z.boolean().optional(),
defaultTestRunner: z.enum(SUPPORTED_TEST_RUNNERS_LIST).optional(),
allowDevelopmentBuild: z.literal(true).optional(),
......
......@@ -335,6 +335,52 @@ export interface LoggingConfig {
browserToTerminal?: boolean | 'error' | 'warn'
}
/**
* All recognized lightningcss feature names.
* Individual features map 1:1 to lightningcss `Features` bitflags.
* Composite names (`selectors`, `media-queries`, `colors`) enable a group of
* related individual features at once.
*
* The name→bitmask mapping is duplicated in:
* - JS: `packages/next/src/build/webpack/loaders/lightningcss-loader/src/features.ts`
* - Rust: `crates/next-core/src/next_config.rs` (`lightningcss_feature_names_to_mask`)
*/
export const LIGHTNINGCSS_FEATURE_NAMES = [
// Individual features (bit 0–20)
'nesting',
'not-selector-list',
'dir-selector',
'lang-selector-list',
'is-selector',
'text-decoration-thickness-percent',
'media-interval-syntax',
'media-range-syntax',
'custom-media-queries',
'clamp-function',
'color-function',
'oklab-colors',
'lab-colors',
'p3-colors',
'hex-alpha-colors',
'space-separated-color-notation',
'font-family-system-ui',
'double-position-gradients',
'vendor-prefixes',
'logical-properties',
'light-dark',
// Composite groups
'selectors',
'media-queries',
'colors',
] as const
export type LightningCssFeature = (typeof LIGHTNINGCSS_FEATURE_NAMES)[number]
export interface LightningCssFeatures {
include?: LightningCssFeature[]
exclude?: LightningCssFeature[]
}
export interface ExperimentalConfig {
adapterPath?: string
appNewScrollHandler?: boolean
......@@ -771,6 +817,13 @@ export interface ExperimentalConfig {
*/
useLightningcss?: boolean
/**
* Configure which CSS features lightningcss should always transpile
* (include) or never transpile (exclude), regardless of browser targets.
* Requires `useLightningcss: true`.
*/
lightningCssFeatures?: LightningCssFeatures
/**
* Enables view transitions by using the {@link https://react.dev/reference/react/ViewTransition ViewTransition} Component.
*/
......
......@@ -1762,6 +1762,17 @@ export default async function loadConfig(
userConfig.reactProductionProfiling = reactProductionProfiling
}
if (
userConfig.experimental?.lightningCssFeatures &&
!userConfig.experimental?.useLightningcss &&
bundler !== Bundler.Turbopack
) {
curLog.warn(
`experimental.lightningCssFeatures is set but experimental.useLightningcss is not enabled. ` +
`The lightningCssFeatures option has no effect without useLightningcss.`
)
}
if (userConfig.experimental?.useLightningcss) {
const { loadBindings } =
require('../build/swc') as typeof import('../build/swc')
......
.themed {
color: light-dark(black, white);
background-color: light-dark(white, black);
}
import { ReactNode } from 'react'
import './globals.css'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <div className="themed">Hello</div>
}
import { nextTestSetup } from 'e2e-utils'
/** Collect all CSS reachable from a page (inline <style> + linked .css). */
async function collectPageCss(
next: ReturnType<typeof nextTestSetup>['next'],
path: string
): Promise<string> {
const html = await (await next.fetch(path)).text()
let css = ''
// Inline <style> blocks
for (const m of html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)) {
css += m[1]
}
// External <link> stylesheets (href may contain query strings like ?dpl=...)
for (const m of html.matchAll(/<link[^>]*href="([^"]*\.css[^"]*?)"[^>]*>/g)) {
const res = await next.fetch(m[1])
if (res.ok) css += await res.text()
}
return css
}
describe('experimental-lightningcss-features', () => {
describe('include', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: { lightningcss: '^1.23.0' },
// Chrome 123 supports light-dark() natively — using it here proves that
// the `include` flag forces transpilation regardless of browser support.
packageJson: {
browserslist: ['chrome 123'],
},
nextConfig: {
experimental: {
useLightningcss: true,
lightningCssFeatures: {
include: ['light-dark'],
},
},
},
})
it('should transpile light-dark() when included in lightningCssFeatures', async () => {
const html = await next.render('/')
expect(html).toContain('Hello')
// lightningcss transpiles light-dark(a, b) into fallback custom
// properties: var(--lightningcss-light, a) var(--lightningcss-dark, b).
const css = await collectPageCss(next, '/')
expect(css).not.toContain('light-dark(')
expect(css).toContain('--lightningcss-light')
expect(css).toContain('--lightningcss-dark')
})
})
describe('exclude', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: { lightningcss: '^1.23.0' },
// Chrome 100 does NOT support light-dark() natively, so lightningcss would
// normally transpile it. Using `exclude: ['light-dark']` should prevent that.
packageJson: {
browserslist: ['chrome 100'],
},
nextConfig: {
experimental: {
useLightningcss: true,
lightningCssFeatures: {
exclude: ['light-dark'],
},
},
},
})
it('should preserve light-dark() when excluded from lightningCssFeatures', async () => {
const html = await next.render('/')
expect(html).toContain('Hello')
// With `exclude: ['light-dark']`, lightningcss should NOT transpile
// light-dark() — the raw function should remain in the output.
const css = await collectPageCss(next, '/')
expect(css).toContain('light-dark(')
expect(css).not.toContain('--lightningcss-light')
expect(css).not.toContain('--lightningcss-dark')
})
})
})
......@@ -18,7 +18,7 @@ use turbopack_core::{
};
use crate::{
CssModuleAssetType,
CssModuleAssetType, LightningCssFeatureFlags,
chunk::{CssChunkItem, CssChunkItemContent, CssChunkPlaceable, CssChunkType, CssImport},
code_gen::CodeGenerateable,
process::{
......@@ -39,6 +39,7 @@ pub struct CssModuleAsset {
import_context: Option<ResolvedVc<ImportContext>>,
ty: CssModuleAssetType,
environment: Option<ResolvedVc<Environment>>,
lightningcss_features: LightningCssFeatureFlags,
}
#[turbo_tasks::value_impl]
......@@ -51,6 +52,7 @@ impl CssModuleAsset {
ty: CssModuleAssetType,
import_context: Option<ResolvedVc<ImportContext>>,
environment: Option<ResolvedVc<Environment>>,
lightningcss_features: LightningCssFeatureFlags,
) -> Vc<Self> {
Self::cell(CssModuleAsset {
source,
......@@ -58,6 +60,7 @@ impl CssModuleAsset {
import_context,
ty,
environment,
lightningcss_features,
})
}
......@@ -80,6 +83,7 @@ impl ParseCss for CssModuleAsset {
this.import_context.map(|v| *v),
this.ty,
this.environment.as_deref().copied(),
this.lightningcss_features,
))
}
}
......@@ -94,6 +98,7 @@ impl ProcessCss for CssModuleAsset {
Ok(process_css_with_placeholder(
parse_result,
this.environment.as_deref().copied(),
this.lightningcss_features,
))
}
......@@ -117,6 +122,7 @@ impl ProcessCss for CssModuleAsset {
minify_type,
origin_source_map,
this.environment.as_deref().copied(),
this.lightningcss_features,
))
}
}
......
......@@ -43,3 +43,14 @@ pub enum CssModuleAssetType {
/// The CSS is parsed as CSS modules.
Module,
}
/// User-specified lightningcss feature flags (from `experimental.lightningCssFeatures`).
///
/// Both fields are raw `Features` bitmasks. `include` bits are OR-ed into the
/// default feature set; `exclude` bits are masked off.
#[turbo_tasks::value(shared, serialization = "auto")]
#[derive(PartialOrd, Ord, Hash, Copy, Clone, Debug, Default, TaskInput)]
pub struct LightningCssFeatureFlags {
pub include: u32,
pub exclude: u32,
}
......@@ -35,7 +35,7 @@ use turbopack_core::{
};
use crate::{
CssModuleAssetType,
CssModuleAssetType, LightningCssFeatureFlags,
lifetime_util::stylesheet_into_static,
references::{
analyze_references,
......@@ -53,10 +53,15 @@ struct LightningCssTargets(
);
/// Returns the LightningCSS targets for the given browserslist query.
///
/// `extra_include` / `extra_exclude` are raw `Features` bitmasks from user
/// config (`experimental.lightningCssFeatures`). They are OR-ed into (or masked
/// from) the default feature set (`Nesting | MediaRangeSyntax`).
#[turbo_tasks::function]
async fn get_lightningcss_browser_targets(
environment: Option<ResolvedVc<Environment>>,
handle_nesting: bool,
feature_flags: LightningCssFeatureFlags,
) -> Result<Vc<LightningCssTargets>> {
match environment {
Some(environment) => {
......@@ -70,19 +75,19 @@ async fn get_lightningcss_browser_targets(
},
)?;
Ok(if handle_nesting {
Vc::cell(Targets {
browsers: browserslist_browsers,
include: Features::Nesting | Features::MediaRangeSyntax,
..Default::default()
})
} else {
Vc::cell(Targets {
browsers: browserslist_browsers,
include: Features::MediaRangeSyntax,
..Default::default()
})
})
let mut include = Features::MediaRangeSyntax;
if handle_nesting {
include |= Features::Nesting;
}
include |= Features::from_bits_truncate(feature_flags.include);
let exclude = Features::from_bits_truncate(feature_flags.exclude);
include &= !exclude;
Ok(Vc::cell(Targets {
browsers: browserslist_browsers,
include,
exclude,
}))
}
// Default when empty environment is passed.
None => Ok(Vc::cell(Default::default())),
......@@ -97,6 +102,7 @@ async fn stylesheet_to_css(
handle_nesting: bool,
mut origin_source_map: Option<parcel_sourcemap::SourceMap>,
environment: Option<ResolvedVc<Environment>>,
feature_flags: LightningCssFeatureFlags,
) -> Result<CssOutput> {
let mut srcmap = if enable_srcmap {
Some(parcel_sourcemap::SourceMap::new(""))
......@@ -104,8 +110,12 @@ async fn stylesheet_to_css(
None
};
let targets =
*get_lightningcss_browser_targets(environment.as_deref().copied(), handle_nesting).await?;
let targets = *get_lightningcss_browser_targets(
environment.as_deref().copied(),
handle_nesting,
feature_flags,
)
.await?;
let result = ss.to_css(PrinterOptions {
minify: matches!(minify_type, MinifyType::Minify { .. }),
......@@ -193,6 +203,7 @@ pub enum FinalCssResult {
pub async fn process_css_with_placeholder(
parse_result: ResolvedVc<ParseCssResult>,
environment: Option<ResolvedVc<Environment>>,
feature_flags: LightningCssFeatureFlags,
) -> Result<Vc<CssWithPlaceholderResult>> {
let result = parse_result.await?;
......@@ -220,6 +231,7 @@ pub async fn process_css_with_placeholder(
false,
None,
environment,
feature_flags,
)
.await?;
......@@ -252,6 +264,7 @@ pub async fn finalize_css(
minify_type: MinifyType,
origin_source_map: Vc<FileContent>,
environment: Option<ResolvedVc<Environment>>,
feature_flags: LightningCssFeatureFlags,
) -> Result<Vc<FinalCssResult>> {
let result = result.await?;
match &*result {
......@@ -307,6 +320,7 @@ pub async fn finalize_css(
true,
origin_source_map,
environment,
feature_flags,
)
.await?;
......@@ -351,6 +365,7 @@ pub async fn parse_css(
import_context: Option<ResolvedVc<ImportContext>>,
ty: CssModuleAssetType,
environment: Option<ResolvedVc<Environment>>,
feature_flags: LightningCssFeatureFlags,
) -> Result<Vc<ParseCssResult>> {
let span = tracing::info_span!(
"parse css",
......@@ -375,6 +390,7 @@ pub async fn parse_css(
import_context,
ty,
environment,
feature_flags,
)
.await?
}
......@@ -395,6 +411,7 @@ async fn process_content(
import_context: Option<ResolvedVc<ImportContext>>,
ty: CssModuleAssetType,
environment: Option<ResolvedVc<Environment>>,
feature_flags: LightningCssFeatureFlags,
) -> Result<Vc<ParseCssResult>> {
#[allow(clippy::needless_lifetimes)]
fn without_warnings<'o, 'i>(config: ParserOptions<'o, 'i>) -> ParserOptions<'o, 'static> {
......@@ -487,9 +504,12 @@ async fn process_content(
}
}
let targets =
*get_lightningcss_browser_targets(environment.as_deref().copied(), true)
.await?;
let targets = *get_lightningcss_browser_targets(
environment.as_deref().copied(),
true,
feature_flags,
)
.await?;
// minify() is actually transform, and it performs operations like CSS modules
// handling.
......
......@@ -254,13 +254,18 @@ async fn apply_module_type(
.await?,
),
ModuleType::Css { ty, environment } => ResolvedVc::upcast(
ModuleType::Css {
ty,
environment,
lightningcss_features,
} => ResolvedVc::upcast(
CssModuleAsset::new(
*source,
Vc::upcast(module_asset_context),
*ty,
css_import_context.map(|c| *c),
environment.as_deref().copied(),
*lightningcss_features,
)
.to_resolved()
.await?,
......@@ -753,6 +758,7 @@ async fn process_default_internal(
empty_transforms,
default_options,
None,
Default::default(),
)
.await?;
match effect {
......
......@@ -253,6 +253,7 @@ impl ModuleOptions {
enable_raw_css,
source_maps: css_source_maps,
ref module_css_condition,
lightningcss_features,
..
},
ref static_url_tag,
......@@ -491,6 +492,7 @@ impl ModuleOptions {
postprocess,
ecmascript_options_vc,
environment,
lightningcss_features,
)
.await?,
)
......@@ -817,6 +819,7 @@ impl ModuleOptions {
vec![ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Module,
environment,
lightningcss_features,
})],
),
ModuleRule::new(
......@@ -827,6 +830,7 @@ impl ModuleOptions {
vec![ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Default,
environment,
lightningcss_features,
})],
),
]);
......@@ -890,6 +894,7 @@ impl ModuleOptions {
vec![ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Module,
environment,
lightningcss_features,
})],
),
// Ecmascript CSS Modules referencing the actual CSS module to include it
......@@ -903,6 +908,7 @@ impl ModuleOptions {
vec![ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Module,
environment,
lightningcss_features,
})],
),
// Ecmascript CSS Modules referencing the actual CSS module to list the classes
......@@ -916,6 +922,7 @@ impl ModuleOptions {
vec![ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Module,
environment,
lightningcss_features,
})],
),
ModuleRule::new(
......@@ -930,6 +937,7 @@ impl ModuleOptions {
vec![ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Default,
environment,
lightningcss_features,
})],
),
]);
......
......@@ -294,6 +294,9 @@ pub struct CssOptionsContext {
/// `Any(ResourcePathEndsWith(".module.css"), ContentTypeStartsWith("text/css+module"))`
pub module_css_condition: Option<RuleCondition>,
/// User-specified lightningcss feature flags (include/exclude bitmasks).
pub lightningcss_features: turbopack_css::LightningCssFeatureFlags,
pub placeholder_for_future_extensions: (),
}
......
......@@ -142,6 +142,7 @@ pub enum ModuleType {
Css {
ty: CssModuleAssetType,
environment: Option<ResolvedVc<Environment>>,
lightningcss_features: turbopack_css::LightningCssFeatureFlags,
},
StaticUrlJs {
/// The tag that is passed to ChunkingContext::asset_url
......@@ -231,6 +232,7 @@ impl ConfiguredModuleType {
postprocess: ResolvedVc<EcmascriptInputTransforms>,
options: ResolvedVc<EcmascriptOptions>,
environment: Option<ResolvedVc<Environment>>,
lightningcss_features: turbopack_css::LightningCssFeatureFlags,
) -> Result<ModuleRuleEffect> {
Ok(match self {
ConfiguredModuleType::Bytes => {
......@@ -264,6 +266,7 @@ impl ConfiguredModuleType {
ConfiguredModuleType::Css => ModuleRuleEffect::ModuleType(ModuleType::Css {
ty: CssModuleAssetType::Default,
environment,
lightningcss_features,
}),
ConfiguredModuleType::CssModule => ModuleRuleEffect::ModuleType(ModuleType::CssModule),
ConfiguredModuleType::Json => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment