code-fns

raw JSON →
0.11.0 verified Fri May 01 auth: no javascript

code-fns (v0.11.0) is a JavaScript/TypeScript library for syntax highlighting and code visualization that outputs raw text and hex color tokens instead of HTML/CSS. It is designed for non-web rendering targets such as animations and videos, and is the primary highlighting engine for Motion Canvas. The library supports many languages via tree-sitter grammars, includes a diffing function to compute token-level transformations between code blocks (useful for animations), and ships TypeScript types. It is released on npm with an irregular cadence and requires modern EcmaScript features, so bundling/transpilation is left to the consumer. Key differentiators: output is language-agnostic token arrays, not DOM elements; built-in diff/morph support for transitions; no built-in theming—colors come straight from tree-sitter.

error Error: Must call `ready` before accessing `language`
cause `ready` was not called or not awaited before using `language`.
fix
Add await ready({ langs: ['javascript'] }); before accessing language.javascript.
error TypeError: code_fns_1.default is not a function
cause Using CommonJS require() on an ESM-only package.
fix
Switch to ES module import syntax: import { ready } from 'code-fns'.
error Error: Unsupported language 'js'. Supported languages: ...
cause Passing an incorrect language name string.
fix
Use the exact language identifier (e.g., 'javascript' for JS).
breaking Package requires modern EcmaScript features; no transpilation included.
fix Use a bundler or transpiler (e.g., Babel, esbuild, Webpack) in your build step.
gotcha The `ready` function must be awaited before using `language` or `parse`.
fix Always call `await ready({ langs: [...] })` before parsing.
gotcha Language names are case-sensitive and must match exact property keys (e.g., `javascript` not `js`).
fix Refer to the list of supported tree-sitter grammars; use exact spelling.
gotcha The `diff` function returns tokens with a 'morph' property; the output format differs from `parse`.
fix Handle the 'morph' field when rendering (e.g., for animations).
npm install code-fns
yarn add code-fns
pnpm add code-fns

Demonstrates basic usage: import, initialize a language, parse a code string into tokens with colors.

import { ready, language, parse } from 'code-fns';

async function highlight() {
  await ready({ langs: ['javascript'] });
  const js = language.javascript;
  const tokens = parse(js`const x = 42;`);
  console.log(tokens);
  // [
  //   { code: 'const ', color: '#c9d1d9' },
  //   { code: 'x', color: '#79c0ff' },
  //   { code: ' = ', color: '#c9d1d9' },
  //   { code: '42', color: '#a5d6ff' },
  //   { code: ';', color: '#c9d1d9' }
  // ]
}

highlight().catch(console.error);