Developing LaTeX.js
This page is about working on LaTeX.js itself: setting up the repository, building and testing it, the website, and the conventions of the code. To add macros, document classes or packages, see Extending.
LaTeX.js is written in TypeScript. The parser is generated from a PEG grammar by peggy, the library and the CLI are built with Vite, the tests run with Vitest, and the website, including the playground, is built with VitePress.
Setup
You need Node.js 22 or newer (the CI uses Node.js 24) and rsync, which the build uses. Regenerating package.json (see below) also needs sponge from moreutils. The dev container in .devcontainer/ has all of this, including the libraries that Chrome and Firefox need for the screenshot tests.
sh
git clone https://github.com/michael-brade/LaTeX.js.git
cd LaTeX.js
npm install
npx puppeteer browsers install # once if it didn't happen automatically: Chrome/Firefox for screenshot tests
npm run build
npm testCommands
sh
npm run build # library → dist/ (vite.config.ts), CLI → bin/latex.js (vite.cli.config.ts), css/fonts/js → dist/
npm run devbuild # same, unminified, no source maps
npm run typecheck # tsc for src/, test/, and docs/ (including the .vue files)
npm test # vitest run --project unit: all tests except the integration tests
npm run testc # vitest run --coverage --project unit, report in test/coverage/; needs `npm run build`, not devbuild: source maps
npm run test-int # integration tests: npm pack tarball installed into consumer projects (needs a build, network)
npm run devdocs # `vitepress dev docs` (needs a build)
npm run docs # build + generate the website into the gh-pages worktree ./website and commit it there
npm run clean # remove the build output, test/coverage/, the VitePress cache and the website/ worktreeThe tests and the website use the built library from dist/ and bin/, so build first.
Directory Structure
| Path | What |
|---|---|
src/index.ts | library entry (parse, HtmlGenerator, SyntaxError, …) |
src/parser/latex-parser.pegjs | the peggy grammar, compiled by lib/vite-plugin-peggy.ts; its types are hand-written in latex-parser.pegjs.d.ts next to it (keep the two in sync) |
src/generator/ | the generic generator generator.ts, composed of the mixins in this folder, and the HtmlGenerator in html/ |
src/macro-manager.ts, src/macros.ts | macro management: loading the classes of macros, macro types and argument types, the @Macro and @Args decorators |
src/latex/ | the macros: latex.ltx.ts, symbols.ts, the document classes in documentclasses/ and the packages in packages/ |
src/cli.ts | the latex.js command-line tool, built by vite.cli.config.ts into bin/latex.js (all bare imports stay external, including latex.js → dist/) |
src/latex.component.ts | the <latex-js> web component |
src/util/ | small shared modules (Stack, the mixin Constructor type) |
src/css/, public/fonts/, public/js/ | stylesheets, fonts and scripts the generated HTML needs; the build copies them to dist/css/, dist/fonts/ and dist/js/ |
lib/ | build tooling only (Vite and peggy plugins, the KaTeX CSS generator, the vue-tsc wrapper), never imported by src/ |
test/ | the vitest tests (*.test.ts, configured in vitest.config.ts, which is separate from vite.config.ts), with their own tsconfig.json; test/lib/ holds helpers (the puppeteer browsers for the screenshots, the svgdom DOM setup) |
test/fixtures/ | LaTeX sources and their expected HTML, see Fixtures |
test/screenshots/ | the stored screenshots of the fixtures and of the web component |
test/api/ | API examples run by test/api.test.ts, and included in the usage docs |
test/integration/ | files for the integration tests in test/integration.test.ts, see below |
docs/ | the website: the pages are Markdown; config and theme in docs/.vitepress/, the playground in docs/components/ (LtxPlayground.vue, LaTeX.ts); docs/tsconfig.json covers both |
dist/, bin/ | build output (not in git) |
website/ | the generated website, a worktree of the gh-pages branch (not in git) |
The generator and the macros use TC39 decorators; Babel transpiles them in the Vite build.
Tests
npm test runs all tests except the integration tests. To run only some of them, pass files or a filter, e.g. npx vitest run test/cli.test.ts; the Vitest extension for VS Code runs and debugs single tests. DEBUG=chrome npm test (or DEBUG=firefox) shows that browser with its devtools instead of running it headless.
test/fixtures.test.tstranslates the fixtures and compares the HTML,test/cli.test.tsrunsbin/latex.js,test/api.test.tsruns the examples intest/api/: the Node examples withnode, the browser example in Chrome, and it takes screenshots of the web component examples.
Fixtures
The files in test/fixtures/ (and its subdirectories) contain fixtures: a title, the LaTeX source and the expected HTML, each followed by a line with a single .:
paragraphs and newlines
.
first line\\second line\newline third line\par and then a new paragraph as well
.
<div class="body">
<p>first line<br>second line<br>third line</p>
<p>and then a new paragraph as well</p>
</div>
.A line with attributes may come before the title: ! skips the fixture, + runs only the fixtures that have it, and # also takes screenshots of it. The fixtures are translated without hyphenation; line breaks in the HTML are ignored. When a fixture fails, its actual HTML is written to test/html/.
Whitespace in the fixtures is part of the test: .editorconfig and .gitattributes keep their indentation, trailing spaces and line endings as they are. whitespace.tex mixes Unix, Windows and old Mac line endings, which editors normalize when saving, so .vscode/settings.json opens it read-only.
Screenshots
The fixtures with # and the web component examples are rendered in Chrome and Firefox (with puppeteer) and compared with the screenshots in test/screenshots/ (.ch.png for Chrome, .ff.png for Firefox) using BlazeDiff. If there is no stored screenshot yet, the new one is stored. If they differ, the new screenshot is written next to the stored one as .new.png, and the difference as .diff.png (pixels that got darker are green, lighter ones red). If the change is intended, replace the .png with the .new.png; don't commit the .new.png and .diff.png files.
Coverage
npm run testc writes a coverage report to test/coverage/ (open index.html). It needs npm run build: the tests run the bundles in dist/ and bin/, and only their source maps lead back to src/. After a devbuild, the coverage is 0%.
The CI workflow (.github/workflows/node.js.yml) uploads test/coverage/lcov.info to Qlty, which shows the coverage (and maintainability) in the README badges and on pull requests, and to SonarQube Cloud. The workflow has five jobs:
buildtype-checks and builds,testruns the unit tests with coverage on that build,test-integrationruns the integration tests on that build,uploadsends the coverage report to Qlty, andsonaranalyzes the code with SonarQube and sends it the coverage report.
Only upload and sonar may request an OIDC token, and they run no project code. Both are skipped for pull requests from forks, which get no OIDC token.
Integration Tests
npm run test-int runs test/integration.test.ts, the vitest project integration (npm test runs the project unit, plain npx vitest both, see vitest.config.ts). It needs a build and network access, and tests the package the way consumers get it:
- first,
test/integration/pack.shcreates the tarballtest/integration/tmp/latex.js.tgzwithnpm pack, consumerinstalls it into a new project intest/integration/tmp/consumer/and runs the Node API examples and the CLI there; it also type-checks a consumer withstrictand withoutskipLibCheck: an ES module consumer with the module resolutionsbundler,node16andnodenext, and a CommonJS consumer withnode16andnodenext,React appbuilds a Vite + React app that uses the package (itsApp.tsxistest/integration/react-App.tsx) and checks in Chrome that it renders with the LaTeX styles and fonts, and again when React changes its content. The app stays intest/integration/react-app/, so you can try it withnpm run devthere.
Run them when you change the build or the public API: npm run build && npm run test-int.
Website and Playground
npm run devdocs starts the VitePress dev server; the playground is at /playground and compiles LaTeX live into an iframe. In the pages, <latex/> and <tex/> render the logos, and the library examples in Usage are included from test/api/ (with <<<), so they are tested.
vitepress build pre-renders the pages in Node (vitepress dev doesn't), but the playground is client-only (defineClientComponent in playground.md), so its code can use window and document freely and stays out of the server bundle. Test playground changes with a built site too (vitepress build and vitepress preview), not only with devdocs.
The website uses the library from dist/: "latex.js" resolves through exports, and docs/public/latexjs/{css,fonts,js} are symlinks to dist/{css,fonts,js} that npm run prepare creates (it runs on npm ci and npm install; the playground loads them from /latexjs/, vitepress build copies the real files). After changes in src/, rebuild (npm run devbuild is faster) and restart devdocs; for changes of the CSS, fonts or scripts, a rebuild is enough.
npm run docs builds the library and then the website into website/, a worktree of the gh-pages branch (created if it doesn't exist), and commits it there. It doesn't push.
package.json
package.json is generated, so never edit it by hand. The source of truth is the YAML in package.yaml.sh: edit that file, then run ./package.yaml.sh (it pipes the YAML through npx js-yaml into package.json), then npm i. Commit package.yaml.sh, the regenerated package.json and package-lock.json together.
- The YAML in
package.yaml.shis a quoted heredoc (<<'EOF'), so it is passed to js-yaml verbatim:$in scripts needs no escaping. - Chain script steps with
&&, not;, so a failing step stops the script. - Every script must end with
;(a lone;after the last command). npm appends the arguments ofnpm run <script> <args>to the script's command line. Without the;they would extend the last command:npm run clean /would runrimraf … /. With it, they become a separate command, which fails harmlessly. Keep the;when adding or editing scripts, including one-liners (test: vitest run;). preparerunspatch-package(the patches are inpatches/). It isprepare, notpostinstall:prepareruns onnpm install/npm ciin this repository, but not when latex.js is installed as a dependency, wherepostinstallwould run and fail (it needs devDependencies).
Dependencies
- The libraries that Vite bundles into
dist/(katex, @svgdotjs/svg.js) are only needed at build time, so they are devDependencies. dependenciesis meant for the Node CLI (src/cli.ts).hyphenis a dependency because the CLI loads the patterns of languages other than English at runtime (require("hyphen/<lang>")); onlyhyphen/enis bundled.
TypeScript
- All tsconfigs use
module: EsNextandmoduleResolution: Bundler, which thehyphen/en-style subpath imports need. Vite does the transpiling;tscis only used for type checking (noEmit). - Relative imports in the source include the
.tsextension. - Self-imports of
"latex.js"(fromcli.ts, the tests and the docs) resolve like this:- type checking:
customConditions: ["latex.js-source"]maps them tosrc/index.ts. This is set in the root tsconfig and inherited bytest/anddocs/. - runtime (Node, tsx, Vite/VitePress): they resolve through
exportstodist/, so a build is needed.
- type checking:
- Editors use the nearest
tsconfig.jsonin a file's parent folders. That's why the docs' tsconfig isdocs/tsconfig.json, not indocs/.vitepress/: it has to be a parent ofdocs/components/too. Otherwise the editor would check those files against the root tsconfig, which only includessrc/, without the declarations for?raw/?inlineimports (docs/.vitepress/vite-env.d.ts), unless another docs file was opened first. - Two TypeScript versions are installed:
typescript7.x: the compiler (tsc) for type checking, also run by vite-plugin-checker duringvite build.@typescript/typescript66.x: TypeScript 7 has no JavaScript compiler API, so the tools that need it (unplugin-dts, vue-tsc) use this one. It depends on@typescript/old(a realtypescript@6), whose owntscbin collides with the one of TypeScript 7; thepreparescript re-linksnode_modules/.bin/tscto TypeScript 7. Ifnpx tsc -vdoesn't print 7.x, runnpm run prepare.
.vuefiles are type-checked bynode lib/vue-tsc.cjs(part ofnpm run typecheck), which runs vue-tsc with TypeScript 6. Plainnpx vue-tsccrashes, and plaintscignores.vuefiles.
Published Types
- unplugin-dts emits
src/**/*.tstodist/types/**/*.d.ts(entryRoot: "src"), plus a CommonJS copy as*.d.ctsnext to them.exportsinpackage.jsonreferences them directly:import→dist/types/index.d.ts,require→dist/types/index.d.cts. The package is"type": "module", so a CommonJS consumer can't use the.d.tsfiles (TS1479 undernode16). - Published types must not reference devDependencies (peggy, svg.js, …): consumers don't have them. Mark internal members that would leak such types with
/** @internal */(stripInternalis on). - Mixins in
src/generator/that are constrained by an intersection of mixin APIs must declareoverride reset(), even if trivially. Otherwise the emitted.d.tsdeclaresresetas a property, andGenerator'soverride reset()fails with TS2425. - When you change the build or the public API, run
npm run build && npm run test-int, see Integration Tests.
Conventions
- 4-space indentation (see
.editorconfig). Match the style of the code around your change. - The KaTeX stylesheets are generated by
lib/katex-css.mjs(part of the build) from the installedkatex:dist/fonts/katex.cssholds only the@font-facerules, anddist/css/katex.cssthe rest, importing them. Don't add asrc/css/katex.css.@font-faceis ignored in a shadow DOM, so pages that show the output in one (like<latex-js>) loadfonts/cmu.cssandfonts/katex.cssinto the page itself. - Don't use
remin the stylesheets: it is relative to the font size of the page's<html>element, not to the document's, so in a<latex-js>component, it would ignore the font size set in the LaTeX source. Usecalc(n * var(--size))instead. - Don't define lengths that depend on
--sizein:root, :host: a custom property is computed where it is defined, so it would use the--sizeof:root, not the oneapplyLengthsAndGeometryToDom()set on the element that contains the document. Give the default as fallback where the length is used instead, e.g.var(--parindent, calc(1.5 * var(--size))). - When updating
katex, checksrc/css/base.cssagainst KaTeX's class names (e.g..mathnormal, which used to be.mathdefault), and look at the math screenshots. - When you change the behavior or the API, update the documentation in
docs/and theREADME.md. - Don't commit anything from
dist/,website/ordocs/.vitepress/cache/.