作者:Titus Wormer
数学公式
本指南探讨了如何在 MDX 中支持数学公式(LaTeX)。 MDX 支持标准 Markdown 语法(CommonMark)。 这意味着数学公式默认不受支持。 数学公式可以通过 remark 插件 remark-math 启用, 结合 rehype 插件: rehype-katex(KaTeX)或 rehype-mathjax (MathJax)。 与其他 remark 和 rehype 插件一样,它们可以分别在 ProcessorOptions 中的 remarkPlugins 和 rehypePlugins 中传递。 有关插件的更多信息请参见§ 扩展 MDX
假设我们有这样一个 MDX 文件:
# $$\sqrt{a^2 + b^2}$$
上面的带数学公式的 MDX 可以用以下模块转换:
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 compileCompile 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 rehypeKatexRender 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 remarkMathAdd support for math.
- @param options Configuration (optional).
- @returns Nothing.
namespace console
var console: ConsoleThe 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
Consoleclass with methods such asconsole.log(),console.error()andconsole.warn()that can be used to write to any Node.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
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
- @see source
(method) Console.log(message?: any, ...optionalParams: any[]): voidPrints 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) => stringAllows 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 compileCompile 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 fsfunction readFile(path: PathLike | fs.FileHandle, options?: ({
encoding?: null | undefined;
flag?: OpenMode | undefined;
} & EventEmitter<T extends EventMap<T> = DefaultEventMap>.Abortable) | null): Promise<NonSharedBuffer> (+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 | undefinedList of rehype plugins (optional).
(alias) function rehypeKatex(options?: Readonly<Options> | null | undefined): (tree: Root, file: VFile) => undefined
import rehypeKatexRender elements with a language-math (or math-display, math-inline) class with KaTeX.
- @param options Configuration (optional).
- @returns Transform.
(property) remarkPlugins?: PluggableList | null | undefinedList of remark plugins (optional).
(alias) function remarkMath(options?: Readonly<Options> | null | undefined): undefined
import remarkMathAdd support for math.
- @param options Configuration (optional).
- @returns Nothing.
展开等价 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>
</>
重要:如果你选择了 rehype-katex,你还应该在页面上某处使用 katex.css 来正确渲染数学公式的样式。 在撰写本文时,最新版本是:
<!-- 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">
要获取样式表的最新链接,请访问 katex 文档。
**注意:**另见 remark-mdx-math-enhanced, 你可以用它在数学公式中支持 JavaScript 表达式(例如 访问属性或进行计算)