Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 45 additions & 15 deletions napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ struct Config {
#[serde(default)]
pub exclude: u32,
pub minify: Option<bool>,
pub minify_whitespace: Option<bool>,
pub source_map: Option<bool>,
pub input_source_map: Option<String>,
pub drafts: Option<Drafts>,
Expand Down Expand Up @@ -629,6 +630,7 @@ struct BundleConfig {
#[serde(default)]
pub exclude: u32,
pub minify: Option<bool>,
pub minify_whitespace: Option<bool>,
pub source_map: Option<bool>,
pub drafts: Option<Drafts>,
pub non_standard: Option<NonStandard>,
Expand Down Expand Up @@ -753,13 +755,22 @@ fn compile<'i>(
exclude: Features::from_bits_truncate(config.exclude),
};

stylesheet.minify(MinifyOptions {
targets,
unused_symbols: config.unused_symbols.clone().unwrap_or_default(),
})?;
let format_minify = config.minify_whitespace.unwrap_or(config.minify.unwrap_or_default());
let should_optimize = if config.minify_whitespace.is_some() {
config.minify.unwrap_or_default()
} else {
true
};

if should_optimize {
stylesheet.minify(MinifyOptions {
targets,
unused_symbols: config.unused_symbols.clone().unwrap_or_default(),
})?;
}

stylesheet.to_css(PrinterOptions {
minify: config.minify.unwrap_or_default(),
minify: format_minify,
source_map: source_map.as_mut(),
project_root,
targets,
Expand Down Expand Up @@ -889,13 +900,22 @@ fn compile_bundle<
exclude: Features::from_bits_truncate(config.exclude),
};

stylesheet.minify(MinifyOptions {
targets,
unused_symbols: config.unused_symbols.clone().unwrap_or_default(),
})?;
let format_minify = config.minify_whitespace.unwrap_or(config.minify.unwrap_or_default());
let should_optimize = if config.minify_whitespace.is_some() {
config.minify.unwrap_or_default()
} else {
true
};

if should_optimize {
stylesheet.minify(MinifyOptions {
targets,
unused_symbols: config.unused_symbols.clone().unwrap_or_default(),
})?;
}

stylesheet.to_css(PrinterOptions {
minify: config.minify.unwrap_or_default(),
minify: format_minify,
source_map: source_map.as_mut(),
project_root,
targets,
Expand Down Expand Up @@ -951,6 +971,7 @@ struct AttrConfig {
pub exclude: u32,
#[serde(default)]
pub minify: bool,
pub minify_whitespace: Option<bool>,
#[serde(default)]
pub analyze_dependencies: bool,
#[serde(default)]
Expand Down Expand Up @@ -1012,12 +1033,21 @@ fn compile_attr<'i>(
exclude: Features::from_bits_truncate(config.exclude),
};

attr.minify(MinifyOptions {
targets,
..MinifyOptions::default()
});
let format_minify = config.minify_whitespace.unwrap_or(config.minify);
let should_optimize = if config.minify_whitespace.is_some() {
config.minify
} else {
true
};

if should_optimize {
attr.minify(MinifyOptions {
targets,
..MinifyOptions::default()
});
}
attr.to_css(PrinterOptions {
minify: config.minify,
minify: format_minify,
source_map: None,
project_root: None,
targets,
Expand Down
10 changes: 10 additions & 0 deletions node/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ export interface TransformOptions<C extends CustomAtRules> {
code: Uint8Array,
/** Whether to enable minification. */
minify?: boolean,
/**
* Controls whitespace/newline minification during serialization only.
* When omitted, output formatting follows existing `minify` behavior.
*/
minifyWhitespace?: boolean,
/** Whether to output a source map. */
sourceMap?: boolean,
/** An input source map to extend. */
Expand Down Expand Up @@ -417,6 +422,11 @@ export interface TransformAttributeOptions {
code: Uint8Array,
/** Whether to enable minification. */
minify?: boolean,
/**
* Controls whitespace/newline minification during serialization only.
* When omitted, output formatting follows existing `minify` behavior.
*/
minifyWhitespace?: boolean,
/** The browser targets for the generated code. */
targets?: Targets,
/**
Expand Down
77 changes: 74 additions & 3 deletions node/test/bundle.test.mjs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import path from 'path';
import fs from 'fs';
import os from 'os';
import { test } from 'uvu';
import * as assert from 'uvu/assert';
import {webcrypto as crypto} from 'node:crypto';

let bundleAsync;
let bundle, bundleAsync;
if (process.env.TEST_WASM === 'node') {
bundleAsync = (await import('../../wasm/wasm-node.mjs')).bundleAsync;
({ bundle, bundleAsync } = await import('../../wasm/wasm-node.mjs'));
} else if (process.env.TEST_WASM === 'browser') {
// Define crypto globally for old node.
// @ts-ignore
globalThis.crypto ??= crypto;
let wasm = await import('../../wasm/index.mjs');
await wasm.default();
bundle = wasm.bundle;
bundleAsync = function (options) {
if (!options.resolver?.read) {
options.resolver = {
Expand All @@ -24,7 +26,7 @@ if (process.env.TEST_WASM === 'node') {
return wasm.bundleAsync(options);
}
} else {
bundleAsync = (await import('../index.mjs')).bundleAsync;
({ bundle, bundleAsync } = await import('../index.mjs'));
}

test('resolver', async () => {
Expand Down Expand Up @@ -78,6 +80,75 @@ test('resolver', async () => {
if (code !== expected) throw new Error(`\`testResolver()\` failed. Expected:\n${expected}\n\nGot:\n${code}`);
});

test('minifyWhitespace can compact bundle output without semantic minification', async () => {
const { code: buffer } = await bundleAsync({
filename: 'foo.css',
minify: false,
minifyWhitespace: true,
resolver: {
read() {
return '.a { color: red; } .a { color: blue; }';
}
}
});

assert.equal(buffer.toString('utf-8'), '.a{color:red}.a{color:#00f}');
});

test('minifyWhitespace can force pretty bundle output with semantic minification', async () => {
const { code: buffer } = await bundleAsync({
filename: 'foo.css',
minify: true,
minifyWhitespace: false,
resolver: {
read() {
return '.a { color: red; } .a { color: blue; }';
}
}
});
const code = buffer.toString('utf-8');

assert.ok(code.includes('\n'));
assert.ok(code.includes('color: #00f;'));
assert.ok(!code.includes('color: red;'));
});

test('sync bundle supports minifyWhitespace and omitted minify', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lightningcss-bundle-test-'));
const file = path.join(dir, 'foo.css');
fs.writeFileSync(file, '.a { color: red; } .a { color: blue; }');
try {
const compact = bundle({
filename: file,
minifyWhitespace: true,
resolver: {
read(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
}
}).code.toString('utf-8');

assert.equal(compact, '.a{color:red}.a{color:#00f}');

const pretty = bundle({
filename: file,
minify: true,
minifyWhitespace: false,
resolver: {
read(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
}
}).code.toString('utf-8');

assert.ok(pretty.includes('\n'));
assert.ok(pretty.includes('color: #00f;'));
assert.ok(!pretty.includes('color: red;'));
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});

test('only custom read', async () => {
const inMemoryFs = new Map(Object.entries({
'foo.css': `
Expand Down
77 changes: 73 additions & 4 deletions node/test/transform.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ import { test } from 'uvu';
import * as assert from 'uvu/assert';
import {webcrypto as crypto} from 'node:crypto';

let transform, Features;
let transform, transformStyleAttribute, Features;
if (process.env.TEST_WASM === 'node') {
({transform, Features} = await import('../../wasm/wasm-node.mjs'));
({transform, transformStyleAttribute, Features} = await import('../../wasm/wasm-node.mjs'));
} else if (process.env.TEST_WASM === 'browser') {
// Define crypto globally for old node.
// @ts-ignore
globalThis.crypto ??= crypto;
let wasm = await import('../../wasm/index.mjs');
await wasm.default();
({transform, Features} = wasm);
({transform, transformStyleAttribute, Features} = wasm);
} else {
({transform, Features} = await import('../index.mjs'));
({transform, transformStyleAttribute, Features} = await import('../index.mjs'));
}

test('can enable non-standard syntax', () => {
Expand Down Expand Up @@ -68,4 +68,73 @@ test('can disable prefixing', () => {
assert.equal(res.code.toString(), '.foo{user-select:none}');
});

test('minifyWhitespace can compact output without semantic minification', () => {
let res = transform({
filename: 'test.css',
code: Buffer.from('.a { color: red; } .a { color: blue; }'),
minify: false,
minifyWhitespace: true
});

assert.equal(res.code.toString(), '.a{color:red}.a{color:#00f}');
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps adding some tests for at-rules and CSS functions would be beneficial.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 0686196

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work


test('minifyWhitespace can force pretty output with semantic minification', () => {
let res = transform({
filename: 'test.css',
code: Buffer.from('.a { color: red; } .a { color: blue; }'),
minify: true,
minifyWhitespace: false
});

let code = res.code.toString();
assert.ok(code.includes('\n'));
assert.ok(code.includes('color: #00f;'));
assert.ok(!code.includes('color: red;'));
});

test('minifyWhitespace decouples formatting when minify is omitted', () => {
let compact = transform({
filename: 'test.css',
code: Buffer.from('.a { color: red; } .a { color: blue; }'),
minifyWhitespace: true
});
assert.equal(compact.code.toString(), '.a{color:red}.a{color:#00f}');

let pretty = transform({
filename: 'test.css',
code: Buffer.from('.a { color: red; } .a { color: blue; }'),
minifyWhitespace: false
});
let code = pretty.code.toString();
assert.ok(code.includes('\n'));
assert.ok(code.includes('color: red;'));
assert.ok(code.includes('color: #00f;'));
});

test('style attributes support minifyWhitespace override', () => {
let compact = transformStyleAttribute({
filename: 'test.css',
code: Buffer.from('color: yellow; flex: 1 1 auto'),
minify: false,
minifyWhitespace: true
});
assert.equal(compact.code.toString(), 'color:#ff0;flex:auto');

let pretty = transformStyleAttribute({
filename: 'test.css',
code: Buffer.from('color: yellow; flex: 1 1 auto'),
minify: true,
minifyWhitespace: false
});
assert.equal(pretty.code.toString(), 'color: #ff0; flex: auto');

let omittedMinify = transformStyleAttribute({
filename: 'test.css',
code: Buffer.from('color: yellow; flex: 1 1 auto'),
minifyWhitespace: false
});
assert.equal(omittedMinify.code.toString(), 'color: #ff0; flex: auto');
});

test.run();
Loading