Skip to navigation
1 minute read
By Titus Wormer

Math

This guide explores how to support math (LaTeX) in MDX. MDX supports standard markdown syntax (CommonMark). That means math is not supported by default. Math can be enabled by using a remark plugin: remark-math, combined with a rehype plugin: either rehype-katex (KaTeX) or rehype-mathjax (MathJax). Like other remark and rehype plugins, they can be passed in remarkPlugins and rehypePlugins, respectively, in ProcessorOptions. More info on plugins is available in § Extending MDX

Say we have an MDX file like this:

example.mdx
# $$\sqrt{a^2 + b^2}$$

The above MDX with math can be transformed with the following module:

example.js
import fs from 'node:fs/promises'
import {compile} from '@mdx-js/mdx'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'

console.log(
  String(
    await compile(await fs.readFile('example.mdx'), {
      rehypePlugins: [rehypeKatex],
      remarkPlugins: [remarkMath]
    })
  )
)
(alias) module "node:fs/promises"
import fs
(alias) function compile(vfileCompatible: Readonly<Compatible>, compileOptions?: Readonly<CompileOptions> | null | undefined): Promise<VFile>
import compile

Compile MDX to JS.

  • @param vfileCompatible MDX document to parse.
  • @param compileOptions Compile configuration (optional).
  • @return Promise to compiled file.
(alias) function rehypeKatex(options?: Readonly<Options> | null | undefined): (tree: Root, file: VFile) => undefined
import rehypeKatex

Render elements with a language-math (or math-display, math-inline) class with KaTeX.

  • @param options Configuration (optional).
  • @returns Transform.
(alias) function remarkMath(options?: Readonly<Options> | null | undefined): undefined
import remarkMath

Add support for math.

  • @param options Configuration (optional).
  • @returns Nothing.
namespace console
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

  • @since v0.1.100
var String: StringConstructor
(value?: any) => string

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

(alias) compile(vfileCompatible: Readonly<Compatible>, compileOptions?: Readonly<CompileOptions> | null | undefined): Promise<VFile>
import compile

Compile MDX to JS.

  • @param vfileCompatible MDX document to parse.
  • @param compileOptions Compile configuration (optional).
  • @return Promise to compiled file.
(alias) module "node:fs/promises"
import fs
function readFile(path: PathLike | fs.FileHandle, options?: ({
    encoding?: null | undefined;
    flag?: OpenMode | undefined;
} & EventEmitter<T extends EventMap<T> = DefaultEventMap>.Abortable) | null): Promise<Buffer> (+2 overloads)

Asynchronously reads the entire contents of a file.

If no encoding is specified (using options.encoding), the data is returned as a Buffer object. Otherwise, the data will be a string.

If options is a string, then it specifies the encoding.

When the path is a directory, the behavior of fsPromises.readFile() is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned.

An example of reading a package.json file located in the same directory of the running code:

import { readFile } from 'node:fs/promises';
try {
  const filePath = new URL('./package.json', import.meta.url);
  const contents = await readFile(filePath, { encoding: 'utf8' });
  console.log(contents);
} catch (err) {
  console.error(err.message);
}

It is possible to abort an ongoing readFile using an AbortSignal. If a request is aborted the promise returned is rejected with an AbortError:

import { readFile } from 'node:fs/promises';

try {
  const controller = new AbortController();
  const { signal } = controller;
  const promise = readFile(fileName, { signal });

  // Abort the request before the promise settles.
  controller.abort();

  await promise;
} catch (err) {
  // When a request is aborted - err is an AbortError
  console.error(err);
}

Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.

Any specified FileHandle has to support reading.

  • @since v10.0.0
  • @param path filename or FileHandle
  • @return Fulfills with the contents of the file.
(property) rehypePlugins?: PluggableList | null | undefined

List of rehype plugins (optional).

(alias) function rehypeKatex(options?: Readonly<Options> | null | undefined): (tree: Root, file: VFile) => undefined
import rehypeKatex

Render elements with a language-math (or math-display, math-inline) class with KaTeX.

  • @param options Configuration (optional).
  • @returns Transform.
(property) remarkPlugins?: PluggableList | null | undefined

List of remark plugins (optional).

(alias) function remarkMath(options?: Readonly<Options> | null | undefined): undefined
import remarkMath

Add support for math.

  • @param options Configuration (optional).
  • @returns Nothing.
Expand equivalent JSX
output.jsx
<>
  <h1>
    <span className="katex">
      <span className="katex-mathml">
        <math xmlns="http://www.w3.org/1998/Math/MathML"></math>
      </span>
      <span className="katex-html" aria-hidden="true"></span>
    </span>
  </h1>
</>

Important: if you chose rehype-katex, you should also use katex.css somewhere on the page to style math properly. At the time of writing, the last version is:

HTML
<!-- Get the latest one from: https://katex.org/docs/browser -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">

To get the latest link to the stylesheet, go to katex docs.

Note: see also remark-mdx-math-enhanced, which you can use to support JavaScript expressions inside of math (such as to access properties or to make calculations)