Comptime.ts
⚡️ Compile-time evaluation of expressions for smaller bundles or faster startup!
Install / Use
/learn @feathers-studio/Comptime.tsREADME
A dead-simple TypeScript compiler that does one thing really well: enables compile-time evaluation of expressions marked with comptime.
This is useful for optimising your code by moving computations from runtime to compile time. This project was inspired by Bun macros and Zig comptime (hence the name).
Warning: You are responsible for ensuring that the expressions you mark with
comptimeare safe to evaluate at compile time.comptime.tsdoes not perform any isolation. However, comptime imports are only allowed in project files, and not in node_modules. You may however import from node_modules as comptime.
Quick References
Contents
- What is comptime.ts?
- Examples
- Installation
- Usage
- Forcing comptime evaluation
- Using other import attributes
- Running code after comptime evaluation
- How it works
- Limitations
- Best practices
- Troubleshooting
- Supporting the project
- License
What is comptime.ts?
comptime.ts allows you to evaluate expressions at compile time, similar to compile-time macros in other languages. This can help optimise your code by moving computations from runtime to compile time.
Examples
1. Simple sum function
import { sum } from "./sum.ts" with { type: "comptime" };
console.log(sum(1, 2));
Compiles to:
console.log(3);
2. Turn emotion CSS into a zero-runtime CSS library
import { css } from "@emotion/css" with { type: "comptime" };
const style = css`
color: red;
font-size: 16px;
`;
div({ class: style });
Compiles to:
const style = "css-x2wxma";
div({ class: style });
Note: The
@emotion/cssimport got removed from the output. You'll need to somehow add the styles back to your project somehow. See running code after comptime evaluation for an example of emitting the styles as a CSS file. Alternatively, you might write a bundler plugin to import the CSS cache from@emotion/cssand emit them as a CSS file, etc.
3. Calculate constants at compile time
import { ms } from "ms" with { type: "comptime" };
const HOUR = ms("1 hour");
Compiles to:
const HOUR = 3600000;
Apart from function calls and tagged template literals, all sorts of expressions are supported (even more complex cases like index access and imported constants). The only limitation is that the resultant value must be serialisable (see serialisation).
Note: The import statements marked with
type: "comptime"are removed in the output. We assume you have other tooling (like Vite) to handle other unused redundant statements left behind after comptime evaluation.
Installation
bun add comptime.ts
# or
pnpm add comptime.ts
# or
npm install comptime.ts
Usage
With Vite
Add the plugin to your Vite configuration:
import { comptime } from "comptime.ts/vite";
export default defineConfig({
plugins: [comptime()],
});
In case comptime.ts is significantly slowing down your dev server, and your comptime functions behave identically at runtime and comptime, you may enable it only in production builds:
import { comptime } from "comptime.ts/vite";
export default defineConfig({
build: {
rollupOptions: {
plugins: [comptime()],
},
},
});
With Bun bundler
Add the plugin to your Bun bundler configuration:
import { comptime } from "comptime.ts/bun";
await Bun.build({
entrypoints: ["./index.ts"],
outdir: "./out",
plugins: [comptime()],
});
Command Line Interface
You can also use the CLI:
npx comptime.ts --project tsconfig.json --outdir out
Or use Bun if you prefer:
bunx --bun comptime.ts --project tsconfig.json --outdir out
Via API
Use the API directly:
import { comptimeCompiler } from "comptime.ts/api";
await comptimeCompiler({ tsconfigPath: "tsconfig.json" }, "./out");
Forcing comptime evaluation of arbitrary expressions (and resolving promises)
We can abuse the fact that any function imported with the type: "comptime" option will be evaluated at compile time.
This library exports a comptime() function that can be used to force comptime evaluation of an expression. It has to be imported with the "comptime" attribute. Any expressions contained within it will be evaluated at compile time. If the result is a promise, the resolved value will be inlined.
Note: Technically the
comptime()function by itself doesn't do anything by itself. It's an identity function. It's thewith { type: "comptime" }attribute that makes the compiler evaluate the expression at compile time.
import { comptime } from "comptime.ts" with { type: "comptime" };
Use it to force comptime evaluation of an expression.
const x = comptime(1 + 2);
When the compiler is run, the expression will be evaluated at compile time.
const x = 3;
Resolving promises
const x = comptime(Promise.resolve(1 + 2));
When the compiler is run, the promise will be resolved and the result will be inlined at compile time.
const x = 3;
Note: The compiler always resolves promises returned by the evaluation, but this might not reflect in your types, in which case it's useful to use the
comptime()function to infer the correct type.
Opting out of comptime virality
Normally, comptime.ts will eagerly extend comptime to expressions that include a comptime expression.
import { foo } from "./foo.ts" with { type: "comptime" };
const x = foo().bar[1];
Compiles to:
const x = 2;
Notice how the whole expression, foo().bar[1], is evaluated at compile time. You can opt-out of this behaviour by wrapping your expression in parentheses.
const x = (foo().bar)[1];
Compiles to:
<!-- prettier-ignore -->const x = ([1, 2])[1];
In this case, foo().bar is evaluated at comptime, but [1] is left untouched.
Note: Your formatter might remove the extraneous parentheses, so you may need to ignore the line (such as with
prettier-ignorecomments). You are of course free to extract the expression to its own line:const res = foo().bar; const x = res[1];Compiles to:
const res = [1, 2]; const x = res[1];This also results in only
foo().barbeing evaluated at comptime, and doesn't upset your formatter.
Using other import attributes
You can use other import attributes alongside type: "comptime". Support for them depends on the runtime you are using. For instance, to import JSON as at comptime, you can do:
import items from "./items.json" with { type: "comptime+json" };
console.log(items.map(items => items.name));
Compiles to:
console.log(["item1", "item2", "item3"]);
The same applies to other import attributes, such as comptime+text, comptime+bytes, etc., as supported by your runtime.
Since expressions are viral, the entire expression items.map(...) is evaluated at comptime. This is desirable in most cases, since some computation has moved to comptime. See opting out of comptime virality for how to avoid this if needed. You can also assign the imported value to a variable to embed the JSON data in your cod
Related Skills
node-connect
347.6kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
108.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Writing Hookify Rules
108.4kThis skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.
review-duplication
100.2kUse this skill during code reviews to proactively investigate the codebase for duplicated functionality, reinvented wheels, or failure to reuse existing project best practices and shared utilities.
