pub struct StyleSheet<'i, T = DefaultAtRule> {
pub rules: CssRuleList<'i, T>,
pub sources: Vec<String>,
pub source_map_urls: Vec<Option<String>>,
pub license_comments: Vec<CowArcStr<'i>>,
/* private fields */
}Expand description
A CSS style sheet, representing a .css file or inline <style> element.
Style sheets can be parsed from a string, constructed from scratch, or created using a Bundler. Then, they can be minified and transformed for a set of target browsers, and serialied to a string.
§Example
use lightningcss::stylesheet::{
StyleSheet, ParserOptions, MinifyOptions, PrinterOptions
};
// Parse a style sheet from a string.
let mut stylesheet = StyleSheet::parse(
r#"
.foo {
color: red;
}
.bar {
color: red;
}
"#,
ParserOptions::default()
).unwrap();
// Minify the stylesheet.
stylesheet.minify(MinifyOptions::default()).unwrap();
// Serialize it to a string.
let res = stylesheet.to_css(PrinterOptions::default()).unwrap();
assert_eq!(res.code, ".foo, .bar {\n color: red;\n}\n");Fields§
§rules: CssRuleList<'i, T>A list of top-level rules within the style sheet.
sources: Vec<String>A list of file names for all source files included within the style sheet.
Sources are referenced by index in the loc property of each rule.
source_map_urls: Vec<Option<String>>The source map URL extracted from the original style sheet.
license_comments: Vec<CowArcStr<'i>>The license comments that appeared at the start of the file.
Implementations§
Source§impl<'i, 'o> StyleSheet<'i, DefaultAtRule>
impl<'i, 'o> StyleSheet<'i, DefaultAtRule>
Sourcepub fn parse(
code: &'i str,
options: ParserOptions<'i>,
) -> Result<Self, Error<ParserError<'i>>>
pub fn parse( code: &'i str, options: ParserOptions<'i>, ) -> Result<Self, Error<ParserError<'i>>>
Parse a style sheet from a string.
Examples found in repository?
6fn parse() {
7 use lightningcss::stylesheet::{ParserOptions, StyleSheet};
8 use std::{env, fs};
9
10 let args: Vec<String> = env::args().collect();
11 let contents = fs::read_to_string(&args[1]).unwrap();
12 let stylesheet = StyleSheet::parse(
13 &contents,
14 ParserOptions {
15 filename: args[1].clone(),
16 ..ParserOptions::default()
17 },
18 )
19 .unwrap();
20 let json = serde_json::to_string(&stylesheet).unwrap();
21 println!("{}", json);
22}Source§impl<'i, T> StyleSheet<'i, T>
impl<'i, T> StyleSheet<'i, T>
Sourcepub fn new(
sources: Vec<String>,
rules: CssRuleList<'i, T>,
options: ParserOptions<'i>,
) -> StyleSheet<'i, T>
pub fn new( sources: Vec<String>, rules: CssRuleList<'i, T>, options: ParserOptions<'i>, ) -> StyleSheet<'i, T>
Creates a new style sheet with the given source filenames and rules.
Sourcepub fn parse_with<P: AtRuleParser<'i, AtRule = T>>(
code: &'i str,
options: ParserOptions<'i>,
at_rule_parser: &mut P,
) -> Result<Self, Error<ParserError<'i>>>
pub fn parse_with<P: AtRuleParser<'i, AtRule = T>>( code: &'i str, options: ParserOptions<'i>, at_rule_parser: &mut P, ) -> Result<Self, Error<ParserError<'i>>>
Parse a style sheet from a string.
Examples found in repository?
23fn main() {
24 let args: Vec<String> = std::env::args().collect();
25 let source = std::fs::read_to_string(&args[1]).unwrap();
26 let opts = ParserOptions {
27 filename: args[1].clone(),
28 ..Default::default()
29 };
30
31 let mut stylesheet = StyleSheet::parse_with(&source, opts, &mut TailwindAtRuleParser).unwrap();
32
33 println!("{:?}", stylesheet);
34
35 let mut style_rules = HashMap::new();
36 stylesheet
37 .visit(&mut StyleRuleCollector {
38 rules: &mut style_rules,
39 })
40 .unwrap();
41 println!("{:?}", style_rules);
42 stylesheet.visit(&mut ApplyVisitor { rules: &style_rules }).unwrap();
43
44 let result = stylesheet
45 .to_css(PrinterOptions {
46 targets: Browsers {
47 chrome: Some(100 << 16),
48 ..Browsers::default()
49 }
50 .into(),
51 ..PrinterOptions::default()
52 })
53 .unwrap();
54 println!("{}", result.code);
55}Sourcepub fn source_map_url(&self, source_index: usize) -> Option<&String>
pub fn source_map_url(&self, source_index: usize) -> Option<&String>
Returns the source map URL for the source at the given index.
Sourcepub fn source_map(&self, source_index: usize) -> Option<SourceMap>
Available on crate feature sourcemap only.
pub fn source_map(&self, source_index: usize) -> Option<SourceMap>
sourcemap only.Returns the inline source map associated with the source at the given index.
Sourcepub fn minify(
&mut self,
options: MinifyOptions,
) -> Result<(), Error<MinifyErrorKind>>
pub fn minify( &mut self, options: MinifyOptions, ) -> Result<(), Error<MinifyErrorKind>>
Minify and transform the style sheet for the provided browser targets.
Examples found in repository?
20fn observe(case: &Value, provider: &Provider) -> Value {
21 let mut map = SourceMap::new("/");
22 let options = ParserOptions {
23 css_modules: case["cssModules"].as_bool().unwrap_or(false).then(|| Config {
24 dashed_idents: true,
25 pattern: Pattern::parse("[hash]_[local]").unwrap(),
26 ..Default::default()
27 }),
28 ..Default::default()
29 };
30 let mut bundler = Bundler::new(provider, Some(&mut map), options);
31 let result = match bundler.bundle(Path::new(case["entry"].as_str().unwrap())) {
32 Ok(mut stylesheet) => {
33 // Preserve pre-minification source/map/comment/context metadata too.
34 let bundle = json!({
35 "ast": stylesheet,
36 "sources": stylesheet.sources,
37 "sourceMapUrls": stylesheet.source_map_urls,
38 "licenseComments": stylesheet.license_comments,
39 "privateContentHashesObserved": false,
40 });
41 let minify_error = if case["minify"].as_bool().unwrap_or(false) {
42 stylesheet.minify(MinifyOptions::default()).err()
43 } else {
44 None
45 };
46 if let Some(value) = minify_error {
47 json!({"bundle": bundle, "error": error("minify", value)})
48 } else {
49 match stylesheet.to_css(PrinterOptions {
50 source_map: Some(&mut map),
51 ..Default::default()
52 }) {
53 Ok(result) => json!({
54 "bundle": bundle, "code": result.code, "exports": result.exports,
55 "references": result.references, "dependencies": result.dependencies,
56 }),
57 Err(value) => json!({"bundle": bundle, "error": error("print", value)}),
58 }
59 }
60 }
61 Err(value) => json!({"error": error("bundle", value)}),
62 };
63 let mappings: Vec<Value> = map
64 .get_mappings()
65 .iter()
66 .map(|mapping| {
67 json!({
68 "generatedLine": mapping.generated_line,
69 "generatedColumn": mapping.generated_column,
70 "original": mapping.original.map(|value| json!({
71 "line": value.original_line, "column": value.original_column,
72 "source": value.source, "name": value.name,
73 })),
74 })
75 })
76 .collect();
77 json!({
78 "result": result,
79 "map": {"json": map.to_json(None).unwrap(), "sources": map.get_sources(),
80 "sourcesContent": map.get_sources_content(), "names": map.get_names(), "mappings": mappings},
81 })
82}Sourcepub fn to_css(
&self,
options: PrinterOptions<'_>,
) -> Result<ToCssResult, Error<PrinterErrorKind>>
pub fn to_css( &self, options: PrinterOptions<'_>, ) -> Result<ToCssResult, Error<PrinterErrorKind>>
Serialize the style sheet to a CSS string.
Examples found in repository?
23fn main() {
24 let args: Vec<String> = std::env::args().collect();
25 let source = std::fs::read_to_string(&args[1]).unwrap();
26 let opts = ParserOptions {
27 filename: args[1].clone(),
28 ..Default::default()
29 };
30
31 let mut stylesheet = StyleSheet::parse_with(&source, opts, &mut TailwindAtRuleParser).unwrap();
32
33 println!("{:?}", stylesheet);
34
35 let mut style_rules = HashMap::new();
36 stylesheet
37 .visit(&mut StyleRuleCollector {
38 rules: &mut style_rules,
39 })
40 .unwrap();
41 println!("{:?}", style_rules);
42 stylesheet.visit(&mut ApplyVisitor { rules: &style_rules }).unwrap();
43
44 let result = stylesheet
45 .to_css(PrinterOptions {
46 targets: Browsers {
47 chrome: Some(100 << 16),
48 ..Browsers::default()
49 }
50 .into(),
51 ..PrinterOptions::default()
52 })
53 .unwrap();
54 println!("{}", result.code);
55}More examples
20fn observe(case: &Value, provider: &Provider) -> Value {
21 let mut map = SourceMap::new("/");
22 let options = ParserOptions {
23 css_modules: case["cssModules"].as_bool().unwrap_or(false).then(|| Config {
24 dashed_idents: true,
25 pattern: Pattern::parse("[hash]_[local]").unwrap(),
26 ..Default::default()
27 }),
28 ..Default::default()
29 };
30 let mut bundler = Bundler::new(provider, Some(&mut map), options);
31 let result = match bundler.bundle(Path::new(case["entry"].as_str().unwrap())) {
32 Ok(mut stylesheet) => {
33 // Preserve pre-minification source/map/comment/context metadata too.
34 let bundle = json!({
35 "ast": stylesheet,
36 "sources": stylesheet.sources,
37 "sourceMapUrls": stylesheet.source_map_urls,
38 "licenseComments": stylesheet.license_comments,
39 "privateContentHashesObserved": false,
40 });
41 let minify_error = if case["minify"].as_bool().unwrap_or(false) {
42 stylesheet.minify(MinifyOptions::default()).err()
43 } else {
44 None
45 };
46 if let Some(value) = minify_error {
47 json!({"bundle": bundle, "error": error("minify", value)})
48 } else {
49 match stylesheet.to_css(PrinterOptions {
50 source_map: Some(&mut map),
51 ..Default::default()
52 }) {
53 Ok(result) => json!({
54 "bundle": bundle, "code": result.code, "exports": result.exports,
55 "references": result.references, "dependencies": result.dependencies,
56 }),
57 Err(value) => json!({"bundle": bundle, "error": error("print", value)}),
58 }
59 }
60 }
61 Err(value) => json!({"error": error("bundle", value)}),
62 };
63 let mappings: Vec<Value> = map
64 .get_mappings()
65 .iter()
66 .map(|mapping| {
67 json!({
68 "generatedLine": mapping.generated_line,
69 "generatedColumn": mapping.generated_column,
70 "original": mapping.original.map(|value| json!({
71 "line": value.original_line, "column": value.original_column,
72 "source": value.source, "name": value.name,
73 })),
74 })
75 })
76 .collect();
77 json!({
78 "result": result,
79 "map": {"json": map.to_json(None).unwrap(), "sources": map.get_sources(),
80 "sourcesContent": map.get_sources_content(), "names": map.get_names(), "mappings": mappings},
81 })
82}Trait Implementations§
Source§impl<'i, T: Clone> Clone for StyleSheet<'i, T>
impl<'i, T: Clone> Clone for StyleSheet<'i, T>
Source§impl<'i, T: Debug> Debug for StyleSheet<'i, T>
impl<'i, T: Debug> Debug for StyleSheet<'i, T>
Source§impl<'de: 'i, 'i, T> Deserialize<'de> for StyleSheet<'i, T>where
T: Deserialize<'de>,
Available on crate feature serde only.
impl<'de: 'i, 'i, T> Deserialize<'de> for StyleSheet<'i, T>where
T: Deserialize<'de>,
serde only.Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl<'any, 'i, T> IntoOwned<'any> for StyleSheet<'i, T>where
T: IntoOwned<'any>,
Available on crate feature into_owned only.
impl<'any, 'i, T> IntoOwned<'any> for StyleSheet<'i, T>where
T: IntoOwned<'any>,
into_owned only.Source§fn into_owned(self) -> Self::Owned
fn into_owned(self) -> Self::Owned
Consumes the value and returns an owned clone.
Source§impl<'i, T> JsonSchema for StyleSheet<'i, T>where
T: JsonSchema,
Available on crate feature jsonschema only.
impl<'i, T> JsonSchema for StyleSheet<'i, T>where
T: JsonSchema,
jsonschema only.Source§fn schema_name() -> String
fn schema_name() -> String
Source§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Source§fn json_schema(generator: &mut SchemaGenerator) -> Schema
fn json_schema(generator: &mut SchemaGenerator) -> Schema
Source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
$ref keyword. Read moreSource§impl<'i, T> Serialize for StyleSheet<'i, T>where
T: Serialize,
Available on crate feature serde only.
impl<'i, T> Serialize for StyleSheet<'i, T>where
T: Serialize,
serde only.Source§impl<'i, T, V> Visit<'i, T, V> for StyleSheet<'i, T>
Available on crate feature visitor only.
impl<'i, T, V> Visit<'i, T, V> for StyleSheet<'i, T>
visitor only.Source§const CHILD_TYPES: VisitTypes
const CHILD_TYPES: VisitTypes
Auto Trait Implementations§
impl<'i, T> Freeze for StyleSheet<'i, T>where
CssRuleList<'i, T>: Freeze,
impl<'i, T> RefUnwindSafe for StyleSheet<'i, T>where
CssRuleList<'i, T>: RefUnwindSafe,
impl<'i, T> Send for StyleSheet<'i, T>where
CssRuleList<'i, T>: Send,
impl<'i, T> Sync for StyleSheet<'i, T>where
CssRuleList<'i, T>: Sync,
impl<'i, T> Unpin for StyleSheet<'i, T>where
CssRuleList<'i, T>: Unpin,
impl<'i, T> UnsafeUnpin for StyleSheet<'i, T>where
CssRuleList<'i, T>: UnsafeUnpin,
impl<'i, T> UnwindSafe for StyleSheet<'i, T>where
CssRuleList<'i, T>: UnwindSafe,
Blanket Implementations§
Source§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
Source§type ArchivedMetadata = ()
type ArchivedMetadata = ()
Source§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
Source§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
Source§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
Source§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
Source§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out indicating that a T is niched.