Documentation version dev
Documentation
On this page

JavaScript API reference

Reference for the mathconv npm package: installation, loading the WebAssembly module in Node.js, bundlers and browsers, the convert function, the Converter class, results, errors and performance.

You are reading the documentation of the development version on the dev branch, which is not released. The latest release is 0.1.0a4: this page in 0.1.0a4.

The npm package @mathconv/mathconv is the Rust core compiled to WebAssembly, a portable binary format that browsers and JavaScript runtimes execute at close to native speed, with a JavaScript module and TypeScript declarations around it. It converts exactly as the Python package does, so the options, the LaTeX output and the fallbacks described for Python hold here too.

Installation#

npm install @mathconv/mathconv

The package works in Node.js 22.12 and later, Deno 2.9 and later, bundlers such as webpack, Vite and esbuild, and browsers that load ES modules. Deno needs permission to read the package's .wasm file, granted with --allow-read. Other runtimes that follow the node export condition are expected to work but are not tested.

The installed version is the export version, the version of the Python package written as a semantic version: 0.1.0-alpha.4 for 0.1.0a4.

Loading the module#

The WebAssembly module has to be loaded before the first conversion. A call before that throws an Error that says so.

In Node.js and Deno, the package reads the module from disk and instantiates it synchronously when it is imported, so conversions work straight away. In Node.js, require("@mathconv/mathconv") loads the same module from CommonJS.

Everywhere else, call init once and await it:

import { init, convert } from "@mathconv/mathconv";

await init();
convert("<math><mi>x</mi></math>"); // "x"

Without an argument, init fetches the module from its file next to the package's JavaScript, an address that webpack, Vite and browsers loading ES modules resolve by themselves. Other setups pass the module to init: its address, a Response, its bytes or a compiled WebAssembly.Module. The package exports the file as @mathconv/mathconv/mathconv.wasm, so a bundler that turns a file import into an address supplies it. With esbuild, --loader:.wasm=file does that, and --public-path sets where the output directory is served:

import { init } from "@mathconv/mathconv";
import wasm from "@mathconv/mathconv/mathconv.wasm";

await init(wasm);

Where the bytes are already at hand, as in a worker that received them, initSync(bytes) loads the module synchronously. Calls of init and initSync after the first do nothing. The module is about 210 KB compressed with gzip.

When bundling a Node.js program, mark @mathconv/mathconv as external, as for other packages that read files of their own, so that the package finds its module.

Functions#

convert(text, options?) -> string

converts one formula and returns the output as a string. The options object holds the formats, source and target, and the options of Conversion options under the same names, with true and false for True and False. A property that is left out or undefined keeps its default.

import { convert } from "@mathconv/mathconv";

convert("<math><msup><mi>x</mi><mn>2</mn></msup></math>"); // "x^2"
convert("<math><mfrac><mn>1</mn><mi>x</mi></mfrac></math>", { target: "text" }); // "1/x"
convert("<math><mi>x</mi></math>", { delimiters: "paren" }); // "\\(x\\)"

Each call checks its formats and options again, so code that converts many formulas with the same settings is better served by a Converter.

Converter#

const converter = new Converter(options?);
converter.convert(text) -> string
converter.result(text) -> Result
converter.convertBatch(texts) -> string[]
converter.resultBatch(texts) -> Result[]

A converter checks its options once, when it is created, and converts any number of formulas with them. Converters are immutable. The batch methods take an array or any other iterable of strings and return an array with one entry per input, in input order. Each formula is converted on its own, so broken markup in one affects only its own result.

import { Converter } from "@mathconv/mathconv";

const converter = new Converter({ delimiters: "dollar" });
converter.convertBatch(["<math><mi>a</mi></math>", '<math display="block"><mi>b</mi></math>']);
// ["$a$", "$$b$$"]

Result#

result and resultBatch return plain objects with the fields of the Python result, the origin of the output in JavaScript spelling:

FieldTypeValue
outputstringthe formula in the target format
displaybooleanthe display flag
takenFromstring"markup" for converted markup; "annotation" or "alttext" for carried TeX
fallbacksFallback[]every fallback, in input order; empty for carried TeX

A fallback is an object { code, detail }, with the codes listed under Fallbacks:

new Converter().result("<math><mi>x</mi><mstack><mn>12</mn></mstack></math>");
// { output: "x12", display: false, takenFrom: "markup", fallbacks: [{ code: "elementary-math", detail: "mstack" }] }

The TypeScript declarations name the types Options, Result, Fallback and FallbackCode.

Errors#

Creating a converter, or calling convert, with an unknown format, option or option value, or with an option that does not belong to the chosen formats, throws Error. An option value of the wrong type, such as drop_labels: 1, throws TypeError. The message names the problem:

new Converter({ target: "text", delimiters: "dollar" });
// Error: the option `delimiters` does not belong to the chosen formats

An input that is not a string throws TypeError, and so does a single string passed to a batch method. A batch with any item that is not a string throws TypeError, names the item and converts nothing. Nothing else throws: broken or unsupported markup is reported through fallbacks.

Performance#

The JavaScript module writes the inputs of a call directly into WebAssembly memory and receives all outputs of the call in one string, so a batch costs a fixed number of calls between JavaScript and WebAssembly whatever its size. Batches are faster than one call per formula, most of all for short formulas, and convertBatch is faster than resultBatch when only the outputs are needed. Under Node.js the package converts at about half the speed of the Rust core; Throughput describes the measurement, which covers both calls.

WebAssembly runs one call at a time on its thread. To use several cores, convert in several worker threads, each of which loads its own copy of the module.

Edit this page on GitHub