How can keep css comments after codegen?

Hello friends, in rust I can not be able to keep comments for a css file or content for example as you see I return the comments in lexer Some(&comments), but it deletes the comments
pub fn parse(
file_content: &str,
) -> Result<(Stylesheet, SingleThreadedComments, Lrc<SourceMap>), String> {
let cm: Lrc<SourceMap> = Default::default();
let fm = cm.new_source_file(FileName::Anon.into(), file_content.into());

let comments = SingleThreadedComments::default();

let lexer = Lexer::new(
SourceFileInput::from(&*fm),
Some(&comments),
ParserConfig::default(),
);

let mut parser = Parser::new(lexer, ParserConfig::default());

let stylesheet = match parser.parse_all() {
Ok(s) => s,
Err(_) => {
return Err("Failed to parse CSS".to_string());
}
};

Ok((stylesheet, comments, cm))
}
pub fn parse(
file_content: &str,
) -> Result<(Stylesheet, SingleThreadedComments, Lrc<SourceMap>), String> {
let cm: Lrc<SourceMap> = Default::default();
let fm = cm.new_source_file(FileName::Anon.into(), file_content.into());

let comments = SingleThreadedComments::default();

let lexer = Lexer::new(
SourceFileInput::from(&*fm),
Some(&comments),
ParserConfig::default(),
);

let mut parser = Parser::new(lexer, ParserConfig::default());

let stylesheet = match parser.parse_all() {
Ok(s) => s,
Err(_) => {
return Err("Failed to parse CSS".to_string());
}
};

Ok((stylesheet, comments, cm))
}
my css codegen:
let mut output = String::new();
{
let mut writer = BasicCssWriter::new(&mut output, None, Default::default());
let mut gen = CodeGenerator::new(&mut writer, CodegenConfig { minify: false });
gen.emit(&stylesheet).expect("Failed to generate CSS");
}

Ok(output)
let mut output = String::new();
{
let mut writer = BasicCssWriter::new(&mut output, None, Default::default());
let mut gen = CodeGenerator::new(&mut writer, CodegenConfig { minify: false });
gen.emit(&stylesheet).expect("Failed to generate CSS");
}

Ok(output)
Thank you in advance --- Example:
let css_code = r#"
@import "reset.css";
/* This file is for your main application CSS */
body { color: black; }
"#;

let new_imports = r#"
@import "theme.css";
@import "reset.css";
@import "custom.css";
"#;

let result = insert_import_to_ast(css_code, new_imports).unwrap();
println!("{}", result);
let css_code = r#"
@import "reset.css";
/* This file is for your main application CSS */
body { color: black; }
"#;

let new_imports = r#"
@import "theme.css";
@import "reset.css";
@import "custom.css";
"#;

let result = insert_import_to_ast(css_code, new_imports).unwrap();
println!("{}", result);
#### Returns
@import "theme.css";
@import "custom.css";
@import "reset.css";
body {
color: black;
}
@import "theme.css";
@import "custom.css";
@import "reset.css";
body {
color: black;
}
1 Reply
Shahryar
ShahryarOP•4d ago
🥲 🥲 No one has experience with it?

Did you find this page helpful?