Unverified Commit 7ca56e97 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: remove CSS comments when minifying (#77940)

Remove these comments when minification is enabled (= production)
```css
/* [project]/test/integration/css-minify/styles/global.css [client] (css) */
.a{--var-1:-50%;--var-2:-50%}.b{--var-1:0;--var-2:-50%}
```
parent 81cf3968
......@@ -87,53 +87,25 @@ describe.each([
if (process.env.IS_TURBOPACK_TEST) {
if (dependencies.sass) {
expect(sourceMapContentParsed).toMatchInlineSnapshot(`
{
"sections": [
{
"map": {
"mappings": "AAAA,iCAAiC",
"names": [],
"sources": [
"turbopack:///[project]/styles/global.scss.css",
],
"sourcesContent": [
".redText ::placeholder{color:red}.flex-parsing{flex:0 0 calc(50% - var(--vertical-gutter))}",
],
"version": 3,
},
"offset": {
"column": 0,
"line": 1,
},
},
],
"version": 3,
}
{
"mappings": "AAAA,iCAAiC",
"names": [],
"sourcesContent": [
".redText ::placeholder{color:red}.flex-parsing{flex:0 0 calc(50% - var(--vertical-gutter))}",
],
"version": 3,
}
`)
} else {
expect(sourceMapContentParsed).toMatchInlineSnapshot(`
{
"sections": [
{
"map": {
"mappings": "AAAA,iCAAiC",
"names": [],
"sources": [
"turbopack:///[project]/styles/global.scss.css",
],
"sourcesContent": [
".redText ::placeholder{color:red}.flex-parsing{flex:0 0 calc(50% - var(--vertical-gutter))}",
],
"version": 3,
},
"offset": {
"column": 0,
"line": 1,
},
},
],
"version": 3,
}
{
"mappings": "AAAA,iCAAiC",
"names": [],
"sourcesContent": [
".redText ::placeholder{color:red}.flex-parsing{flex:0 0 calc(50% - var(--vertical-gutter))}",
],
"version": 3,
}
`)
}
} else {
......
......@@ -21,12 +21,9 @@ function runTests() {
const href = $('link').attr('href')
const css = await renderViaHTTP(appPort, href)
if (process.env.IS_TURBOPACK_TEST) {
expect(css).toMatchInlineSnapshot(`
"/* [project]/test/integration/css-minify/styles/global.css [client] (css) */
.a{--var-1:-50%;--var-2:-50%}.b{--var-1:0;--var-2:-50%}
/*# sourceMappingURL=5c046e82fcc94f24.css.map*/"
`)
expect(css).toContain(
'.a{--var-1:-50%;--var-2:-50%}.b{--var-1:0;--var-2:-50%}'
)
} else {
expect(css).toMatchInlineSnapshot(
`".a{--var-1:0;--var-2:0;--var-1:-50%;--var-2:-50%}.b{--var-1:0;--var-2:0;--var-2:-50%}"`
......
......@@ -706,12 +706,11 @@ describe('Catch-all Route CSS Module Usage', () => {
)
if (process.env.IS_TURBOPACK_TEST) {
expect(cssContent.replace(/\/\*.*?\*\//g, '').trim())
expect(cssContent.replace(/\/\*.*?\*\/\n?/g, '').trim())
.toMatchInlineSnapshot(`
".index-module___rV4CG__home{background:red}
".index-module___rV4CG__home{background:red}
.\\35 5css-module__qe774W__home{color:green}"
.\\35 5css-module__qe774W__home{color:green}"
`)
} else {
expect(
......
......@@ -308,7 +308,6 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.red-text{color:red}
.blue-text{color:#00f}",
]
`)
......@@ -318,7 +317,6 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.red-text{color:red}
.blue-text{color:#00f}",
]
`)
......@@ -394,13 +392,10 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.red-text{color:purple;font-weight:bolder}
.red-text{color:red}
.blue-text{color:orange;font-weight:bolder}
.blue-text{color:#00f}",
]
`)
......@@ -410,13 +405,10 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.red-text{color:purple;font-weight:bolder}
.red-text{color:red}
.blue-text{color:orange;font-weight:bolder}
.blue-text{color:#00f}",
]
`)
......@@ -493,7 +485,6 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.blue-text{color:#00f}
.red-text{color:red}",
]
`)
......@@ -503,7 +494,6 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.blue-text{color:#00f}
.red-text{color:red}",
]
`)
......@@ -579,10 +569,8 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg),url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
.blue-text{color:#00f}",
]
`)
......@@ -592,10 +580,8 @@ module.exports = {
"/_next/static/chunks/HASH.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg),url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
.blue-text{color:#00f}",
]
`)
......@@ -656,10 +642,8 @@ describe('CSS URL via `file-loader` and asset prefix (1)', () => {
"/_next/static/chunks/HASH.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
.blue-text{color:#00f}",
]
`)
......@@ -712,10 +696,8 @@ describe('CSS URL via `file-loader` and asset prefix (2)', () => {
"/_next/static/chunks/HASH.css:
.red-text{color:red;background-image:url(../media/dark.993bedd3.svg) url(../media/dark2.993bedd3.svg)}
.blue-text{color:orange;background-image:url(../media/light.180573e4.svg);font-weight:bolder}
.blue-text{color:#00f}",
]
`)
......@@ -745,7 +727,7 @@ async function getStylesheetContents($, appPort, items) {
`${href.replace(
/[0-9a-f]{8,}/g,
'HASH'
)}:\n${text.replace(/\/\*.*?\*\//g, '').trim()}`
)}:\n${text.replace(/\/\*.*?\*\/\n?/g, '').trim()}`
)
}
return results
......
......@@ -74,7 +74,7 @@ module.exports = {
).then((res) => res.text())
const cssContentWithoutSourceMap = cssContent
.replace(/\/\*.*?\*\//g, '')
.replace(/\/\*.*?\*\/\n?/g, '')
.trim()
if (process.env.IS_TURBOPACK_TEST && useLightningcss) {
......@@ -118,95 +118,67 @@ module.exports = {
if (process.env.IS_TURBOPACK_TEST && useLightningcss) {
expect(sourceMapContentParsed).toMatchInlineSnapshot(`
{
"sections": [
{
"map": {
"mappings": "AAAA,4BACE,2BAKF,0DAIA,kDAIA,uCAIA",
"names": [],
"sources": [
"turbopack:///[project]/test/integration/css-fixtures/compilation-and-prefixing/styles/global.css",
],
"sourcesContent": [
"@media (480px <= width < 768px) {
::placeholder {
color: green;
}
}
{
"mappings": "AAAA,4BACE,2BAKF,0DAIA,kDAIA,uCAIA",
"names": [],
"sourcesContent": [
"@media (480px <= width < 768px) {
::placeholder {
color: green;
}
}
.flex-parsing {
flex: 0 0 calc(50% - var(--vertical-gutter));
}
.flex-parsing {
flex: 0 0 calc(50% - var(--vertical-gutter));
}
.transform-parsing {
transform: translate3d(0px, 0px);
}
.transform-parsing {
transform: translate3d(0px, 0px);
}
.css-grid-shorthand {
grid-column: span 2;
}
.css-grid-shorthand {
grid-column: span 2;
}
.g-docs-sidenav .filter::-webkit-input-placeholder {
opacity: 80%;
}
",
],
"version": 3,
},
"offset": {
"column": 0,
"line": 1,
},
},
],
"version": 3,
}
.g-docs-sidenav .filter::-webkit-input-placeholder {
opacity: 80%;
}
",
],
"version": 3,
}
`)
} else if (process.env.IS_TURBOPACK_TEST && !useLightningcss) {
expect(sourceMapContentParsed).toMatchInlineSnapshot(`
{
"sections": [
{
"map": {
"mappings": "AAAA,4BACE,2BAKF,0DAIA,kDAIA,uCAIA",
"names": [],
"sources": [
"turbopack:///[project]/test/integration/css-fixtures/compilation-and-prefixing/styles/global.css",
],
"sourcesContent": [
"@media (480px <= width < 768px) {
::placeholder {
color: green;
}
}
{
"mappings": "AAAA,4BACE,2BAKF,0DAIA,kDAIA,uCAIA",
"names": [],
"sourcesContent": [
"@media (480px <= width < 768px) {
::placeholder {
color: green;
}
}
.flex-parsing {
flex: 0 0 calc(50% - var(--vertical-gutter));
}
.flex-parsing {
flex: 0 0 calc(50% - var(--vertical-gutter));
}
.transform-parsing {
transform: translate3d(0px, 0px);
}
.transform-parsing {
transform: translate3d(0px, 0px);
}
.css-grid-shorthand {
grid-column: span 2;
}
.css-grid-shorthand {
grid-column: span 2;
}
.g-docs-sidenav .filter::-webkit-input-placeholder {
opacity: 80%;
}
",
],
"version": 3,
},
"offset": {
"column": 0,
"line": 1,
},
},
],
"version": 3,
}
.g-docs-sidenav .filter::-webkit-input-placeholder {
opacity: 80%;
}
",
],
"version": 3,
}
`)
} else if (useLightningcss) {
expect(sourceMapContentParsed).toMatchInlineSnapshot(`
......@@ -459,10 +431,10 @@ module.exports = {
res.text()
)
)
.replace(/\/\*.*?\*\//g, '')
.replace(/\/\*.*?\*\/\n?/g, '')
.trim()
expect(cssContent.replace(/\/\*.*?\*\//g, '').trim()).toMatch(
expect(cssContent.replace(/\/\*.*?\*\/\n?/g, '').trim()).toMatch(
/nprogress/
)
})
......@@ -519,32 +491,30 @@ module.exports = {
res.text()
)
)
.replace(/\/\*.*?\*\//g, '')
.replace(/\/\*.*?\*\/\n?/g, '')
.trim()
if (process.env.IS_TURBOPACK_TEST && useLightningcss) {
expect(cssContent.replace(/\/\*.*?\*\//g, '').trim())
expect(cssContent.replace(/\/\*.*?\*\/\n?/g, '').trim())
.toMatchInlineSnapshot(`
".other{color:#00f}
.test{color:red}"
`)
} else if (process.env.IS_TURBOPACK_TEST && !useLightningcss) {
expect(cssContent.replace(/\/\*.*?\*\//g, '').trim())
expect(cssContent.replace(/\/\*.*?\*\/\n?/g, '').trim())
.toMatchInlineSnapshot(`
".other{color:#00f}
.test{color:red}"
`)
} else if (useLightningcss) {
expect(
cssContent.replace(/\/\*.*?\*\//g, '').trim()
cssContent.replace(/\/\*.*?\*\/\n?/g, '').trim()
).toMatchInlineSnapshot(`".other{color:#00f}.test{color:red}"`)
} else {
expect(
cssContent.replace(/\/\*.*?\*\//g, '').trim()
cssContent.replace(/\/\*.*?\*\/\n?/g, '').trim()
).toMatchInlineSnapshot(`".other{color:blue}.test{color:red}"`)
}
})
......
......@@ -281,7 +281,7 @@ impl BrowserChunkingContext {
*self.chunk_suffix_path
}
/// Returns the minify type.
/// Returns the source map type.
pub fn source_maps_type(&self) -> SourceMapsType {
self.source_maps_type
}
......@@ -510,6 +510,11 @@ impl ChunkingContext for BrowserChunkingContext {
Vc::cell(self.enable_tracing)
}
#[turbo_tasks::function]
pub fn minify_type(&self) -> Vc<MinifyType> {
self.minify_type.cell()
}
#[turbo_tasks::function]
async fn chunk_group(
self: ResolvedVc<Self>,
......
......@@ -37,20 +37,8 @@ pub enum MangleType {
Deterministic,
}
#[derive(
Debug,
TaskInput,
Clone,
Copy,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
TraceRawVcs,
DeterministicHash,
NonLocalValue,
)]
#[turbo_tasks::value(shared)]
#[derive(Debug, TaskInput, Clone, Copy, Hash, DeterministicHash)]
pub enum MinifyType {
// TODO instead of adding a new property here,
// refactor that to Minify(MinifyOptions) to allow defaults on MinifyOptions
......@@ -209,6 +197,10 @@ pub trait ChunkingContext {
Vc::cell(false)
}
fn minify_type(self: Vc<Self>) -> Vc<MinifyType> {
MinifyType::NoMinify.cell()
}
fn async_loader_chunk_item(
&self,
module: Vc<Box<dyn ChunkableModule>>,
......
......@@ -337,9 +337,4 @@ impl CssChunkItem for CssModuleChunkItem {
.into())
}
}
#[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*self.chunking_context
}
}
......@@ -18,8 +18,8 @@ use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{
round_chunk_item_size, AsyncModuleInfo, Chunk, ChunkItem, ChunkItemBatchGroup,
ChunkItemOrBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
ChunkableModule, ChunkingContext, ModuleId, OutputChunk, OutputChunkRuntimeInfo,
ChunkItemExt, ChunkItemOrBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
ChunkableModule, ChunkingContext, MinifyType, OutputChunk, OutputChunkRuntimeInfo,
},
code_builder::{Code, CodeBuilder},
ident::AssetIdent,
......@@ -78,8 +78,6 @@ impl CssChunk {
let mut body = CodeBuilder::new(source_maps);
let mut external_imports = FxIndexSet::default();
for css_item in &this.content.await?.chunk_items {
let id = &*css_item.id().await?;
let content = &css_item.content().await?;
for import in &content.imports {
if let CssImport::External(external_import) = import {
......@@ -87,7 +85,14 @@ impl CssChunk {
}
}
writeln!(body, "/* {} */", id)?;
if matches!(
&*this.chunking_context.minify_type().await?,
MinifyType::NoMinify
) {
let id = &*css_item.id().await?;
writeln!(body, "/* {} */", id)?;
}
let close = write_import_context(&mut body, content.import_context).await?;
let source_map = if *self
......@@ -254,7 +259,7 @@ impl OutputChunk for CssChunk {
let entries_chunk_items = &content.chunk_items;
let included_ids = entries_chunk_items
.iter()
.map(|chunk_item| CssChunkItem::id(**chunk_item).to_resolved())
.map(|chunk_item| chunk_item.id().to_resolved())
.try_join()
.await?;
let imports_chunk_items: Vec<_> = entries_chunk_items
......@@ -382,27 +387,6 @@ impl GenerateSourceMap for CssChunk {
}
}
#[turbo_tasks::value]
pub struct CssChunkContext {
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
}
#[turbo_tasks::value_impl]
impl CssChunkContext {
#[turbo_tasks::function]
pub fn of(chunking_context: ResolvedVc<Box<dyn ChunkingContext>>) -> Vc<CssChunkContext> {
CssChunkContext { chunking_context }.cell()
}
#[turbo_tasks::function]
pub async fn chunk_item_id(
self: Vc<Self>,
chunk_item: Vc<Box<dyn CssChunkItem>>,
) -> Result<Vc<ModuleId>> {
Ok(ModuleId::String(chunk_item.asset_ident().to_string().owned().await?).cell())
}
}
// TODO: remove
#[turbo_tasks::value_trait]
pub trait CssChunkPlaceable: ChunkableModule + Module + Asset {}
......@@ -430,10 +414,6 @@ pub struct CssChunkItemContent {
#[turbo_tasks::value_trait]
pub trait CssChunkItem: ChunkItem {
fn content(self: Vc<Self>) -> Vc<CssChunkItemContent>;
fn chunking_context(self: Vc<Self>) -> Vc<Box<dyn ChunkingContext>>;
fn id(self: Vc<Self>) -> Vc<ModuleId> {
CssChunkContext::of(CssChunkItem::chunking_context(self)).chunk_item_id(self)
}
}
#[turbo_tasks::function]
......
......@@ -6,7 +6,7 @@ use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{rope::RopeBuilder, File, FileSystemPath};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{Chunk, ChunkItem, ChunkingContext},
chunk::{Chunk, ChunkItem, ChunkItemExt, ChunkingContext, MinifyType},
code_builder::{Code, CodeBuilder},
ident::AssetIdent,
introspect::Introspectable,
......@@ -55,9 +55,13 @@ impl SingleItemCssChunk {
.await?;
let mut code = CodeBuilder::new(source_maps);
let id = &*this.item.id().await?;
writeln!(code, "/* {} */", id)?;
if matches!(
&*this.chunking_context.minify_type().await?,
MinifyType::NoMinify
) {
let id = this.item.id().await?;
writeln!(code, "/* {} */", id)?;
}
let content = this.item.content().await?;
let close = write_import_context(&mut code, content.import_context).await?;
......
......@@ -248,6 +248,11 @@ impl ChunkingContext for NodeJsChunkingContext {
Vc::cell(self.enable_file_tracing)
}
#[turbo_tasks::function]
pub fn minify_type(&self) -> Vc<MinifyType> {
self.minify_type.cell()
}
#[turbo_tasks::function]
async fn asset_url(&self, ident: Vc<FileSystemPath>) -> Result<Vc<RcStr>> {
let asset_path = ident.await?.to_string();
......
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