Lightning CSS with Deno
What is Lightning CSS?
From lightningcss.dev:
An extremely fast CSS parser, transformer, bundler, and minifier.
Lightning CSS can replace PostCSS in many cases. For instance, if you want to write “regular” CSS with PostCSS where you eventually end up with a single CSS file, you’d most likely would need to install:
postcss
, autoprefixer
, postcss-import
, postcss-nesting
.
Lightning CSS does all of the above out of the box. Pretty nice!
Usage example
Let’s look at an example.
@/css.ts
:
import { debounce } from "https://deno.land/[email protected]/async/debounce.ts"
import { bundle } from "npm:[email protected]"
const HAS_BUILD_FLAG = Deno.args.includes("--build")
async function buildStyles(minify = false) {
const { code } = bundle({
filename: "styles/index.css",
minify,
})
await Deno.writeTextFile("static/styles.css", new TextDecoder().decode(code))
}
if (HAS_BUILD_FLAG) {
console.info("> Building styles for production.")
buildStyles(true)
} else {
await buildStyles()
console.info("> Watching styles.")
const watcher = Deno.watchFs(["styles/"])
const buildCall = debounce(buildStyles, 150)
for await (const _event of watcher) {
buildCall()
}
}
Of course this could be better, but still, it’s pretty simple. It checks for a
--build
flag to decide whether to:
- a) Build the styles for production (minify the output).
- b) Start a watcher and build the styles every time they are updated.
In either case, a single CSS file is written to @/static/styles.css
.
In our @/deno.json
we could then have two tasks:
{
"tasks": {
"dev:css": "deno run -A css.ts",
"build:css": "deno run -A css.ts --build"
}
}