Skip to content

Instantly share code, notes, and snippets.

@podhmo
Last active February 17, 2025 15:03
Show Gist options
  • Save podhmo/69b1d15c83e4234ea62b386527632720 to your computer and use it in GitHub Desktop.
Save podhmo/69b1d15c83e4234ea62b386527632720 to your computer and use it in GitHub Desktop.
esbuildでのcssの扱いを調べたい

esbuildでのcssの扱いを調べたい

たしかjsからimportしたときにも良いかんじに扱われる。はず。

https://esbuild.github.io/content-types/#css

  • bundle css esbuild --bundle app.css --outfile=out.css
  • from js esbuild --bundle --outfile=app.js hello.js
  • css modules (defaultでは <name>.module.css')
$ make

.
├── Makefile
├── README.md
├── base.css
├── code.module.css
├── dist
│   ├── app.css
│   └── app.js
├── hello.js
└── index.html

bundle css

単にbundleされるだけ

from js

jsの中でcssをimportするとjsと同名のprefixをファイル名として持つcssが生成される(app.js, app.css)。

css modules

<name>.module.css という形式のファイルをjsからimportすると良いかんじにファイル名をprefixとして使う code.module.css の .normal が .code_normal に変換される。

/* base.css */
body {
padding: 2rem;
}
p {
background-color: #ffa;
padding: 1rem;
}
/* code.module.css */
.code_normal {
background-color: #aaf;
padding: 1rem;
}
(() => {
// code.module.css
var normal = "code_normal";
// hello.js
console.log("hello");
var el = document.createElement("pre");
el.className = normal;
el.textContent = "console.log(`hello`);";
document.body.appendChild(el);
})();
body {
padding: 2rem;
}
p {
background-color: #ffa;
padding: 1rem;
}
.normal {
background-color: #aaf;
padding: 1rem;
}
import "./base.css"
import { normal } from "./code.module.css"
console.log("hello")
const el = document.createElement("pre");
el.className = normal; // css modules (as .code_normal)
el.textContent = "console.log(`hello`);"
document.body.appendChild(el)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="./dist/app.css" rel="stylesheet" />
</head>
<body>
<h1>hello</h1>
<p>hello hello</p>
</body>
<script src="./dist/app.js"></script>
</html>
default:
esbuild --bundle --outfile=dist/app.js hello.js
.PHONY: default
clean:
rm -rf dist
.PHONY: clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment