Skip to content

Commit

Permalink
Integrate CSS with bundler (oven-sh#14281)
Browse files Browse the repository at this point in the history
Co-authored-by: Jarred Sumner <[email protected]>
Co-authored-by: Zack Radisic <[email protected]>
Co-authored-by: zackradisic <[email protected]>
Co-authored-by: Zack Radisic <[email protected]>
  • Loading branch information
5 people authored Oct 5, 2024
1 parent 3ab3dec commit a01f9d8
Show file tree
Hide file tree
Showing 49 changed files with 3,803 additions and 1,455 deletions.
18 changes: 18 additions & 0 deletions docs/bundler/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,24 @@ $ bun build ./index.tsx --outdir ./out --loader .png:dataurl --loader .txt:file

{% /codetabs %}

### `experimentalCss`

Whether to enable *experimental* support for bundling CSS files. Defaults to `false`.

This supports bundling CSS files imported from JS, as well as CSS entrypoints.

{% codetabs group="a" %}

```ts#JavaScript
const result = await Bun.build({
entrypoints: ["./index.ts"],
experimentalCss: true,
});
// => { success: boolean, outputs: BuildArtifact[], logs: BuildMessage[] }
```

{% /codetabs %}

## Outputs

The `Bun.build` function returns a `Promise<BuildOutput>`, defined as:
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"build:release:local": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -DWEBKIT_LOCAL=ON -B build/release",
"build:release:with_logs": "cmake . -DCMAKE_BUILD_TYPE=Release -DENABLE_LOGS=true -GNinja -Bbuild-release && ninja -Cbuild-release",
"build:debug-zig-release": "cmake . -DCMAKE_BUILD_TYPE=Release -DZIG_OPTIMIZE=Debug -GNinja -Bbuild-debug-zig-release && ninja -Cbuild-debug-zig-release",
"css-properties": "bun run src/css/properties/generate_properties.ts",
"bump": "bun ./scripts/bump.ts",
"typecheck": "tsc --noEmit && cd test && bun run typecheck",
"fmt": "bun run prettier",
Expand Down
7 changes: 7 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1595,6 +1595,13 @@ declare module "bun" {
* @default false
*/
bytecode?: boolean;

/**
* **Experimental**
*
* Enable CSS support.
*/
experimentalCss?: boolean;
}

namespace Password {
Expand Down
28 changes: 27 additions & 1 deletion src/baby_list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ pub fn BabyList(comptime Type: type) type {
return l.swapRemove(index);
}

pub fn sortAsc(
this: *@This(),
) void {
bun.strings.sortAsc(this.slice());
}

pub fn contains(this: @This(), item: []const Type) bool {
return this.len > 0 and @intFromPtr(item.ptr) >= @intFromPtr(this.ptr) and @intFromPtr(item.ptr) < @intFromPtr(this.ptr) + this.len;
}
Expand Down Expand Up @@ -77,8 +83,17 @@ pub fn BabyList(comptime Type: type) type {
};
}

fn assertValidDeepClone(comptime T: type) void {
return switch (T) {
bun.JSAst.Expr, bun.JSAst.G.Property, bun.css.ImportConditions => {},
else => {
@compileError("Unsupported type for BabyList.deepClone(): " ++ @typeName(Type));
},
};
}

pub fn deepClone(this: @This(), allocator: std.mem.Allocator) !@This() {
if (comptime Type != bun.JSAst.Expr and Type != bun.JSAst.G.Property) @compileError("Unsupported type for BabyList.deepClone()");
assertValidDeepClone(Type);
var list_ = try initCapacity(allocator, this.len);
for (this.slice()) |item| {
list_.appendAssumeCapacity(try item.deepClone(allocator));
Expand All @@ -87,6 +102,17 @@ pub fn BabyList(comptime Type: type) type {
return list_;
}

/// Same as `deepClone` but doesn't return an error
pub fn deepClone2(this: @This(), allocator: std.mem.Allocator) @This() {
assertValidDeepClone(Type);
var list_ = initCapacity(allocator, this.len) catch bun.outOfMemory();
for (this.slice()) |item| {
list_.appendAssumeCapacity(item.deepClone(allocator));
}

return list_;
}

pub fn clearRetainingCapacity(this: *@This()) void {
this.len = 0;
}
Expand Down
5 changes: 5 additions & 0 deletions src/bun.js/api/JSBundler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ pub const JSBundler = struct {
packages: options.PackagesOption = .bundle,
format: options.Format = .esm,
bytecode: bool = false,
experimental_css: bool = false,

pub const List = bun.StringArrayHashMapUnmanaged(Config);

Expand All @@ -94,6 +95,10 @@ pub const JSBundler = struct {
errdefer this.deinit(allocator);
errdefer if (plugins.*) |plugin| plugin.deinit();

if (config.getTruthy(globalThis, "experimentalCss")) |enable_css| {
this.experimental_css = if (enable_css.isBoolean()) enable_css.toBoolean() else false;
}

// Plugins must be resolved first as they are allowed to mutate the config JSValue
if (try config.getArray(globalThis, "plugins")) |array| {
var iter = array.arrayIterator(globalThis);
Expand Down
1 change: 0 additions & 1 deletion src/bun.js/javascript.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2742,7 +2742,6 @@ pub const VirtualMachine = struct {
)) {
.success => |r| r,
.failure => |e| {
{}
this.log.addErrorFmt(
null,
logger.Loc.Empty,
Expand Down
8 changes: 7 additions & 1 deletion src/bun.js/node/types.zig
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,13 @@ pub fn Maybe(comptime ReturnTypeT: type, comptime ErrorTypeT: type) type {
err: ErrorType,
result: ReturnType,

pub const Tag = enum { err, result };
/// NOTE: this has to have a well defined layout (e.g. setting to `u8`)
/// experienced a bug with a Maybe(void, void)
/// creating the `err` variant of this type
/// resulted in Zig incorrectly setting the tag, leading to a switch
/// statement to just not work.
/// we (Zack, Dylan, Dave, Mason) observed that it was set to 0xFF in ReleaseFast in the debugger
pub const Tag = enum(u8) { err, result };

pub const retry: @This() = if (hasRetry) .{ .err = ErrorType.retry } else .{ .err = ErrorType{} };

Expand Down
2 changes: 2 additions & 0 deletions src/bun_js.zig
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ pub const Run = struct {
b.resolver.opts.minify_identifiers = ctx.bundler_options.minify_identifiers;
b.resolver.opts.minify_whitespace = ctx.bundler_options.minify_whitespace;

b.options.experimental_css = ctx.bundler_options.experimental_css;

// b.options.minify_syntax = ctx.bundler_options.minify_syntax;

switch (ctx.debug.macros) {
Expand Down
11 changes: 4 additions & 7 deletions src/bundler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -934,11 +934,8 @@ pub const Bundler = struct {
Output.panic("TODO: dataurl, base64", .{}); // TODO
},
.css => {
if (comptime bun.FeatureFlags.css) {
const Arena = @import("../src/mimalloc_arena.zig").Arena;

var arena = Arena.init() catch @panic("oopsie arena no good");
const alloc = arena.allocator();
if (bundler.options.experimental_css) {
const alloc = bundler.allocator;

const entry = bundler.resolver.caches.fs.readFileWithAllocator(
bundler.allocator,
Expand All @@ -953,11 +950,11 @@ pub const Bundler = struct {
};
const source = logger.Source.initRecycledFile(.{ .path = file_path, .contents = entry.contents }, bundler.allocator) catch return null;
_ = source; //
switch (bun.css.StyleSheet(bun.css.DefaultAtRule).parse(alloc, entry.contents, bun.css.ParserOptions.default(alloc, bundler.log))) {
switch (bun.css.StyleSheet(bun.css.DefaultAtRule).parse(alloc, entry.contents, bun.css.ParserOptions.default(alloc, bundler.log), null)) {
.result => |v| {
const result = v.toCss(alloc, bun.css.PrinterOptions{
.minify = bun.getenvTruthy("BUN_CSS_MINIFY"),
}) catch |e| {
}, null) catch |e| {
bun.handleErrorReturnTrace(e, @errorReturnTrace());
return null;
};
Expand Down
Loading

0 comments on commit a01f9d8

Please sign in to comment.