Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/css loader #13

Merged
merged 29 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
159e3f1
implement css & scss loader
gwleuverink Feb 13, 2024
0786711
refactor
gwleuverink Feb 13, 2024
d693f9d
fix typo
gwleuverink Feb 13, 2024
45b34db
update config & env keys
gwleuverink Feb 14, 2024
e0578b1
add tests & refactor
gwleuverink Feb 14, 2024
4cbe027
disable css sourcemaps for now
gwleuverink Feb 14, 2024
f70ac54
boyscouting
gwleuverink Feb 14, 2024
713df92
update workflow triggers
gwleuverink Feb 14, 2024
158479c
update docs
gwleuverink Feb 15, 2024
38e74e5
add browser targeting to CSS loader plugin
gwleuverink Feb 15, 2024
89d803a
refactor
gwleuverink Feb 15, 2024
bef72ac
enable caching by default. also in dev environments
gwleuverink Feb 15, 2024
df84d6b
fix test env
gwleuverink Feb 15, 2024
66c437f
move css loading docs to new page
gwleuverink Feb 16, 2024
2828ec1
prepare scaffold for sass support
gwleuverink Feb 16, 2024
b9cfa51
add dd utility
gwleuverink Feb 16, 2024
b7e05c5
add tests for sass support
gwleuverink Feb 16, 2024
53d38a8
add sass support & handle missing dependencies gracefully
gwleuverink Feb 16, 2024
a0f8c09
add exit util
gwleuverink Feb 16, 2024
a43b915
improve exception handling (needs work)
gwleuverink Feb 16, 2024
70d5b44
boyscouting
gwleuverink Feb 16, 2024
d31976b
fix package.json resolution in testing environment
gwleuverink Feb 16, 2024
9a6632c
refactor
gwleuverink Feb 16, 2024
800a23f
add css sourcemaps
gwleuverink Feb 17, 2024
a3546a3
add browserslist to workbench package.json
gwleuverink Feb 17, 2024
5ac71f8
add sass sourcemaps
gwleuverink Feb 18, 2024
44fbe4c
update css loading docs
gwleuverink Feb 20, 2024
47dae87
disable browser caching in dusk tests
gwleuverink Feb 20, 2024
9deb0ca
Merge branch 'main' into feature/css-loader
gwleuverink Feb 20, 2024
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
2 changes: 1 addition & 1 deletion src/Bundlers/Bun.php → src/Bundlers/Bun/Bun.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace Leuverink\Bundle\Bundlers;
namespace Leuverink\Bundle\Bundlers\Bun;

use SplFileInfo;
use Illuminate\Support\Facades\Process;
Expand Down
64 changes: 64 additions & 0 deletions src/Bundlers/Bun/bin/bun.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { parseArgs } from "util";
import cssLoader from "./plugins/css-loader";

const options = parseArgs({
args: Bun.argv,
strict: true,
allowPositionals: true,

options: {
entrypoint: {
type: "string",
},

inputPath: {
type: "string",
},

outputPath: {
type: "string",
},

sourcemaps: {
type: "boolean",
},

minify: {
type: "boolean",
},
},
}).values;

const result = await Bun.build({
entrypoints: [options.entrypoint],
publicPath: options.outputPath,
outdir: options.outputPath,
root: options.inputPath,
minify: options.minify,

sourcemap: options.sourcemaps ? "external" : "none",

naming: {
entry: '[dir]/[name].[ext]',
chunk: "chunks/[name]-[hash].[ext]", // Not in use without --splitting
asset: "assets/[name]-[hash].[ext]", // Not in use without --splitting
},

target: "browser",
format: "esm",

plugins: [
cssLoader({
minify: options.minify,
sourcemaps: options.sourcemaps
})
]
});

if (!result.success) {
console.error("Build failed");
for (const message of result.logs) {
console.error(message);
}
process.exit(1); // Exit with an error code
}
65 changes: 65 additions & 0 deletions src/Bundlers/Bun/bin/plugins/css-loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { transform, browserslistToTargets } from "lightningcss-wasm";
import { readFile } from "fs/promises";

const defaultOptions = {
targets: [],
minify: true
};

export default function (options = {}) {

return {
name: "css-loader",
async setup(build) {

build.onLoad({ filter: /\.css$|\.scss$/ }, async (args) => {

const css = await compile(args, { ...defaultOptions, ...options })

return {
contents: `export default ${css};`,
loader: "js",
}
})
}
}
}

const compile = async function (args, opts) {

const imports = [];
const source = await readFile(args.path, "utf8");
const targets = opts.targets?.length
? browserslistToTargets(opts.targets)
: undefined;

const { code } = transform({
code: Buffer.from(source),
filename: args.path,

minify: opts.minify,
sourceMap: opts.sourcemaps,
targets,
visitor: {
Rule: {
import(rule) {
imports.push(rule.value.url);
return [];
},
},
},
});

const css = JSON.stringify(code.toString())

if (!imports.length) {
return css
}

const imported = imports
.map((url, i) => `import _css${i} from "${url}";`)
.join("\n");
const exported = imports.map((_, i) => `_css${i}`).join(" + ");

return `${imported}\nexport default ${exported} + ${css};`
}
56 changes: 0 additions & 56 deletions src/Bundlers/bin/bun.js

This file was deleted.

15 changes: 11 additions & 4 deletions src/Components/Import.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ public function render()
}
}

/** Builds the core JavaScript & packages it up in a bundle */
/** Builds the imported JavaScript & packages it up in a bundle */
protected function bundle()
{
$js = $this->core();
$js = $this->import();

// Render script tag with bundled code
return view('x-import::script', [
Expand Down Expand Up @@ -58,8 +58,8 @@ protected function raiseConsoleErrorOrException(BundlingFailedException $e)
HTML;
}

/** Builds Bundle's core JavaScript */
protected function core(): string
/** Builds a bundle for the JavaScript import */
protected function import(): string
{
return <<< JS
//--------------------------------------------------------------------------
Expand All @@ -84,6 +84,13 @@ protected function core(): string
}
}

// Handle CSS injection & return early (no need to add css to import map)
if('{$this->module}'.endsWith('.css') || '{$this->module}'.endsWith('.scss')) {
return import('{$this->module}').then(result => {
window.x_inject_styles(result.default, previous)
})
}

// Assign the import to the window.x_import_modules object (or invoke IIFE)
'{$this->as}'
// Assign it under an alias
Expand Down
17 changes: 17 additions & 0 deletions src/InjectCore.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,23 @@ protected function core(): string
}
};

//--------------------------------------------------------------------------
// Inject styles
//--------------------------------------------------------------------------
window.x_inject_styles = function (css, scriptTag) {
if (typeof document === 'undefined') {
return;
}

// TODO: Add CSP nonce when adding CSP support
const style = document.createElement('style');
style.dataset['module'] = scriptTag.dataset['module'];
style.innerHTML = css;

// Inject the style tag after the script that invoked this function
scriptTag.parentNode.insertBefore(style, scriptTag.nextSibling);
}

JS;
}
}
2 changes: 1 addition & 1 deletion src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

namespace Leuverink\Bundle;

use Leuverink\Bundle\Bundlers\Bun;
use Leuverink\Bundle\Commands\Build;
use Leuverink\Bundle\Commands\Clear;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Leuverink\Bundle\Bundlers\Bun\Bun;
use Leuverink\Bundle\Components\Import;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
Expand Down
Loading