vite-plugin-compile-time
raw JSON → 0.4.6 verified Mon Apr 27 auth: no javascript
A Vite plugin that evaluates JavaScript/TypeScript code at build time and inlines the result into the bundle. Version 0.4.6, actively maintained, with frequent releases. Supports both inline `compileTime()` calls and standalone `.compile.ts` files. Handles JSON-serializable data, RegExp, Date, Map, Set, BigInt, ArrayBuffer, TypedArray, Response, and Buffer. ESM-only, requires Node.js, compatible with Vite >=2.
Common errors
error Error: 'compileTime' is not defined ↓
cause Missing plugin registration or incorrect import
fix
Ensure vite-plugin-compile-time is added to vite.config.ts and compileTime is imported correctly (default import).
error TypeError: fs.readFileSync is not a function ↓
cause Running code in browser environment where 'fs' is not available
fix
Move compile-time code to a separate file or ensure it only uses Node.js APIs that work at build time.
error SyntaxError: await is only valid in async functions ↓
cause Using top-level await inside a `.compile.ts` file without proper async handling
fix
Wrap async code in an async function and use
compileTime() to inline the result, or use top-level await only if supported (Node >=14.8). Warnings
gotcha `compileTime()` must be called at the top level of a module, not inside a function or closure. ↓
fix Move any `compileTime()` call to the module's top-level scope.
gotcha File executed by `compileTime` runs in Node.js. Browser APIs like `document` or `window` are unavailable. ↓
fix Only use Node.js APIs inside compile-time code. Use separate files for browser-related logic.
gotcha `.compile.ts` files are evaluated as modules; importing them in runtime code triggers bundle splitting, not compile-time inlining. ↓
fix Export values directly without `compileTime` wrapper; the plugin handles evaluation automatically.
Install
npm install vite-plugin-compile-time yarn add vite-plugin-compile-time pnpm add vite-plugin-compile-time Imports
- default wrong
import { compileTime } from 'vite-plugin-compile-time'correctimport compileTime from 'vite-plugin-compile-time' - compileTime (runtime helper) wrong
compileTime.call(null, expr)correctconst data = compileTime(expression) - client types wrong
import 'vite-plugin-compile-time/client'correct/// <reference types="vite-plugin-compile-time/client" />
Quickstart
// vite.config.ts
import { defineConfig } from 'vite'
import compileTime from 'vite-plugin-compile-time'
export default defineConfig({
plugins: [compileTime()]
})
// source.ts
import fs from 'fs'
const content = compileTime(fs.readFileSync('./README.md', 'utf8'))
export { content }