Skip to content

Commit

Permalink
perf: use browserslist-rs for lightningcss
Browse files Browse the repository at this point in the history
  • Loading branch information
JSerFeng committed Aug 12, 2024
1 parent fe1bbe9 commit 29e112e
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 45 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ async-recursion = { version = "1.1.0" }
async-scoped = { version = "0.9.0" }
async-trait = { version = "0.1.79" }
bitflags = { version = "2.5.0" }
browserslist-rs = { version = "0.16.0" }
concat-string = "1.0.1"
css-module-lexer = "0.0.14"
dashmap = { version = "5.5.3" }
Expand Down
2 changes: 1 addition & 1 deletion crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1313,7 +1313,7 @@ export interface RawLightningCssBrowsers {

export interface RawLightningCssMinimizerOptions {
errorRecovery: boolean
targets?: RawLightningCssBrowsers
targets?: Array<string>
include?: number
exclude?: number
draft?: RawDraft
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_binding_options/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ignored = ["tracing"]

[dependencies]
async-trait = { workspace = true }
browserslist-rs = { workspace = true }
derivative = { workspace = true }
glob = { workspace = true }
napi = { workspace = true, features = ["async", "tokio_rt", "serde-json", "anyhow"] }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use napi_derive::napi;
use rspack_binding_values::{into_asset_conditions, RawAssetConditions};
use rspack_error::Result;
use rspack_plugin_lightning_css_minimizer::{
Browsers, Draft, MinimizerOptions, NonStandard, PluginOptions, PseudoClasses,
Draft, MinimizerOptions, NonStandard, PluginOptions, PseudoClasses,
};

#[derive(Debug)]
Expand All @@ -22,7 +22,7 @@ pub struct RawLightningCssMinimizerRspackPluginOptions {
#[napi(object)]
pub struct RawLightningCssMinimizerOptions {
pub error_recovery: bool,
pub targets: Option<RawLightningCssBrowsers>,
pub targets: Option<Vec<String>>,
pub include: Option<u32>,
pub exclude: Option<u32>,
pub draft: Option<RawDraft>,
Expand Down Expand Up @@ -79,17 +79,15 @@ impl TryFrom<RawLightningCssMinimizerRspackPluginOptions> for PluginOptions {
remove_unused_local_idents: value.remove_unused_local_idents,
minimizer_options: MinimizerOptions {
error_recovery: value.minimizer_options.error_recovery,
targets: value.minimizer_options.targets.map(|t| Browsers {
android: t.android,
chrome: t.chrome,
edge: t.edge,
firefox: t.firefox,
ie: t.ie,
ios_saf: t.ios_saf,
opera: t.opera,
safari: t.safari,
samsung: t.samsung,
}),
targets: value
.minimizer_options
.targets
.map(|t| {
rspack_loader_lightningcss::lightningcss::targets::Browsers::from_browserslist(t)
})
.transpose()
.map_err(|e| rspack_error::error!("Failed to parser browserslist: {}", e))?
.flatten(),
include: value.minimizer_options.include,
exclude: value.minimizer_options.exclude,
draft: value.minimizer_options.draft.map(|d| Draft {
Expand Down
13 changes: 9 additions & 4 deletions crates/rspack_binding_options/src/plugins/js_loader/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,17 @@ pub fn get_builtin_loader(builtin: &str, options: Option<&str>) -> BoxLoader {
}

if builtin.starts_with(LIGHTNINGCSS_LOADER_IDENTIFIER) {
let config = serde_json::from_str(options.unwrap_or("{}")).unwrap_or_else(|e| {
panic!("Could not parse builtin:lightningcss-loader options:{options:?},error: {e:?}")
});
let config: rspack_loader_lightningcss::config::RawConfig =
serde_json::from_str(options.unwrap_or("{}")).unwrap_or_else(|e| {
panic!("Could not parse builtin:lightningcss-loader options:{options:?},error: {e:?}")
});
// TODO: builtin-loader supports function
return Arc::new(rspack_loader_lightningcss::LightningCssLoader::new(
None, config, builtin,
None,
config.try_into().unwrap_or_else(|e| {
panic!("Could not parse builtin:lightningcss-loader options:{options:?},error: {e:?}")
}),
builtin,
));
}

Expand Down
37 changes: 35 additions & 2 deletions crates/rspack_loader_lightningcss/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ pub struct PseudoClasses {
pub focus_within: Option<String>,
}

#[derive(Debug, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
#[derive(Debug, Default)]
pub struct Config {
pub error_recovery: Option<bool>,
pub targets: Option<Browsers>,
Expand All @@ -35,3 +34,37 @@ pub struct Config {
pub pseudo_classes: Option<PseudoClasses>,
pub unused_symbols: Option<Vec<String>>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct RawConfig {
pub error_recovery: Option<bool>,
pub targets: Option<Vec<String>>,
pub include: Option<u32>,
pub exclude: Option<u32>,
pub draft: Option<Draft>,
pub non_standard: Option<NonStandard>,
pub pseudo_classes: Option<PseudoClasses>,
pub unused_symbols: Option<Vec<String>>,
}

impl TryFrom<RawConfig> for Config {
type Error = rspack_error::Error;
fn try_from(value: RawConfig) -> Result<Self, Self::Error> {
Ok(Self {
error_recovery: value.error_recovery,
targets: value
.targets
.map(|target| lightningcss::targets::Browsers::from_browserslist(target))

Check failure on line 58 in crates/rspack_loader_lightningcss/src/config.rs

View workflow job for this annotation

GitHub Actions / Rust check

redundant closure
.transpose()
.map_err(|err| rspack_error::error!("Failed to parse browserslist: {}", err))?
.flatten(),
include: value.include,
exclude: value.exclude,
draft: value.draft,
non_standard: value.non_standard,
pseudo_classes: value.pseudo_classes,
unused_symbols: value.unused_symbols,
})
}
}
5 changes: 3 additions & 2 deletions crates/rspack_loader_lightningcss/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::borrow::Cow;

use config::Config;
use derivative::Derivative;
pub use lightningcss;
use lightningcss::{
printer::{PrinterOptions, PseudoClasses},
stylesheet::{MinifyOptions, ParserFlags, ParserOptions, StyleSheet},
Expand All @@ -13,7 +14,7 @@ use rspack_error::Result;
use rspack_loader_runner::{Identifiable, Identifier};
use tokio::sync::Mutex;

mod config;
pub mod config;

pub const LIGHTNINGCSS_LOADER_IDENTIFIER: &str = "builtin:lightningcss-loader";

Expand Down Expand Up @@ -98,7 +99,7 @@ impl LightningCssLoader {
}

let targets = Targets {
browsers: self.config.targets,
browsers: self.config.targets.clone(),

Check failure on line 102 in crates/rspack_loader_lightningcss/src/lib.rs

View workflow job for this annotation

GitHub Actions / Rust check

using `clone` on type `Option<Browsers>` which implements the `Copy` trait
include: self
.config
.include
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
const rspack = require('@rspack/core')
const browserslist = require('browserslist')

/** @type {import("@rspack/core").Configuration} */
module.exports = {
module: {
Expand All @@ -18,7 +15,7 @@ module.exports = {
/** @type {import("@rspack/core").LightningcssLoaderOptions} */
options: {
unusedSymbols: ['unused'],
targets: browserslist('> 0.2%')
targets: '> 0.2%'
}
}
],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import {
BuiltinPluginName,
type RawLightningCssBrowsers,
type RawLightningCssMinimizerRspackPluginOptions
} from "@rspack/binding";

import browserslist from "browserslist";
import {
type Drafts,
type FeatureOptions,
type NonStandard,
type PseudoClasses,
type Targets,
browserslistToTargets,
toFeatures
} from "../builtin-loader/lightningcss";
import type { AssetConditions } from "../util/assetCondition";
Expand All @@ -24,7 +20,7 @@ export type LightningCssMinimizerRspackPluginOptions = {
removeUnusedLocalIdents?: boolean;
minimizerOptions?: {
errorRecovery?: boolean;
targets?: Targets | string[] | string;
targets?: string[] | string;
include?: FeatureOptions;
exclude?: FeatureOptions;
draft?: Drafts;
Expand Down Expand Up @@ -56,12 +52,7 @@ export const LightningCssMinimizerRspackPlugin = create(
: // exclude all features, avoid downgrade css syntax when minimize
// 1048575 = Features.Empty | Features.Nesting | ... | Features.LogicalProperties
1048575,
targets:
typeof targets === "string" || Array.isArray(targets)
? (browserslistToTargets(
browserslist(targets)
) as RawLightningCssBrowsers)
: targets,
targets: typeof targets === "string" ? [targets] : targets,
draft: draft ? { customMedia: draft.customMedia ?? false } : undefined,
nonStandard: nonStandard
? {
Expand Down
10 changes: 2 additions & 8 deletions packages/rspack/src/config/adapterRuleUse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import type { Module } from "../Module";
import { resolvePluginImport } from "../builtin-loader";
import {
type FeatureOptions,
browserslistToTargets,
toFeatures
} from "../builtin-loader/lightningcss";
import { type LoaderObject, parsePathQueryFragment } from "../loader-runner";
Expand All @@ -26,7 +25,6 @@ import type {
RuleSetUseItem,
Target
} from "./zod";
import browserslist = require("browserslist");

export const BUILTIN_LOADER_PREFIX = "builtin:";

Expand Down Expand Up @@ -213,12 +211,8 @@ const getSwcLoaderOptions: GetLoaderOptions = (o, _) => {

const getLightningcssLoaderOptions: GetLoaderOptions = (o, _) => {
if (o && typeof o === "object") {
if (o.targets && typeof o.targets === "string") {
o.targets = browserslistToTargets(browserslist(o.targets));
}

if (o.targets && Array.isArray(o.targets)) {
o.targets = browserslistToTargets(browserslist(o.targets));
if (typeof o.targets === "string") {
o.targets = [o.targets];
}

if (o.include && typeof o.include === "object") {
Expand Down

0 comments on commit 29e112e

Please sign in to comment.