1. Introduction
  2. Guidance
  3. 1. Get started
  4. 2. Bundles
    1. 2.1. All-in-One Library for Browsers
    2. 2.2. All-in-One Library for Node.js
  5. 3. Compilers
    1. 3.1. (Pre-)Compiler in CLI
    2. 3.2. Compiler in Rust
    3. 3.3. Compiler in Node.js
    4. 3.4. Compiler in Wasm (Web)
  6. 4. Renderers
    1. 4.1. Renderer in Rust
    2. 4.2. Renderer in Node.js
    3. 4.3. Renderer in Wasm (Web)
    4. 4.4. Renderer in React
    5. 4.5. Renderer in Solid
    6. 4.6. Renderer in Angular
    7. 4.7. Renderer in Vue3
    8. 4.8. Hexo Plugin
  7. 5. Samples
    1. 5.1. Static, Responsive rendering
    2. 5.2. Streaming, Incremental rendering
    3. 5.3. Serverless rendering
  8. 6. Trouble Shooting
  9. Project samples
  10. 8. shiroa
  11. 9. typst-preview
  12. 10. hexo-renderer-typst
  13. References
  14. 13. Routing to Renferences

reflexo-typst Documentation

Claim: the Typst compiling functions is provided by official typst

Note: the following content is for typst.ts >=v0.6.0. To use rust library in <v0.6.0, check the section.

The all-in-one library provides a simplified API, and you can easily compile typst documents into artifacts. For example, compiling a typst code string to a SVG:


        
await $typst.svg({mainContent: 'Hello, typst!' }))

        
await $typst.svg({mainContent: 'Hello, typst!' }))

However, it is less flexible and stable than the underlying interfaces, the TypstCompiler and TypstRenderer. If you've become more familiar with typst.ts, we recommend you rewrite your library with underlying interfaces according to example usage. The best ways to use the underlying libraries can be discovered in the source code of the all-in-one library, the snippet.mts. For example, the above example calls the underlying components:


        
$typst.svg(options) <=>

        
  // Initializes lazily

        
  compiler = createTypstCompiler(); // TypstCompiler

        
  await compiler.init(...)

        
  renderer = createTypstRenderer(); // TypstRenderer

        
  await renderer.init(...)

        
  

        
  // Adds main file content: 'Hello, typst!'

        
  await this.addSource(`/tmp/${randstr()}.typ`, options.mainContent);

        
  // Compiles it

        
  vectorData = options.vectorData || compiler.compile(options)

        
  return renderer.runWithSession(session => {

        
    renderer.manipulateData({ session, action: 'reset', data: vectorData })

        
    // Renders it

        
    renderer.renderSvg({ ...options, session })

        
  })

        
$typst.svg(options) <=>

        
  // Initializes lazily

        
  compiler = createTypstCompiler(); // TypstCompiler

        
  await compiler.init(...)

        
  renderer = createTypstRenderer(); // TypstRenderer

        
  await renderer.init(...)

        
  

        
  // Adds main file content: 'Hello, typst!'

        
  await this.addSource(`/tmp/${randstr()}.typ`, options.mainContent);

        
  // Compiles it

        
  vectorData = options.vectorData || compiler.compile(options)

        
  return renderer.runWithSession(session => {

        
    renderer.manipulateData({ session, action: 'reset', data: vectorData })

        
    // Renders it

        
    renderer.renderSvg({ ...options, session })

        
  })

#

When to use this library (Wasm v.s. napi)

typst.ts runs official typst compiler and its customized renderers in Wasm modules. This is suitable for running in browser, but not very fit in Node.js applications. This is because:

  • Slower Speed: The compiler for browsers is in Wasm module and slower than running compiler as native code.
  • Complex API: You must carefully maintain the bundle size of your browser applications, Therefore, the components are split for better tree-shaking. This will increase code complexity.
  • Network Access: It doesn't bundle the fonts, so has to load them from network.

In other words, the Node.js library achieves:

  • Faster Speed: The Node.js library runs compiler as native code, thus native performance.
  • Simple API: The compiler and renderer are integrated into a same Node.js library for simpler and cleaner APIs.
  • Rich Fonts: The compiler simply use embedded or system fonts for Node.js but not that for web.

If you want to run typst in Node.js using the napi, please see All-in-one Library for Node.js.

#

Installing Bundles from CDN

We provide two bundles for the all-in-one library:

  • all-in-one.bundle.js, it bundles all of the resources to run a typst compiler. You can download the single bundle file and run the compiler offline.
  • all-in-one-lite.bundle.js, the fonts and Wasm modules are excluded to reduce the bundle size. This will cause the script to load extra resources from CDN.

Using all-in-one.bundle.js:


        
<script

        
  type="module"

        
  src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-all-in-one.ts@0.6.0/dist/esm/index.js"

        
  id="typst"

        
>

        
  console.log($typst.svg({

        
    mainContent: 'Hello, typst!',

        
  }));

        
</script>

        
<script

        
  type="module"

        
  src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-all-in-one.ts@0.6.0/dist/esm/index.js"

        
  id="typst"

        
>

        
  console.log($typst.svg({

        
    mainContent: 'Hello, typst!',

        
  }));

        
</script>

Or all-in-one-lite.bundle.js which needs configure your frontend to have access to wasm module files:


        
<script

        
  type="module"

        
  src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst.ts/dist/esm/contrib/all-in-one-lite.bundle.js"

        
  id="typst"

        
>

        
  /// Initializes the Typst compiler and renderer. Since we use "all-in-one-lite.bundle.js" instead of

        
  /// "all-in-one.bundle.js" we need to tell that the wasm module files can be loaded from CDN (jsdelivr).

        
  $typst.setCompilerInitOptions({

        
    getModule: () =>

        
      'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm',

        
  });

        
  $typst.setRendererInitOptions({

        
    getModule: () =>

        
      'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm',

        
  });

        
  

        
  console.log($typst.svg({

        
    mainContent: 'Hello, typst!',

        
  }));

        
</script>

        
<script

        
  type="module"

        
  src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst.ts/dist/esm/contrib/all-in-one-lite.bundle.js"

        
  id="typst"

        
>

        
  /// Initializes the Typst compiler and renderer. Since we use "all-in-one-lite.bundle.js" instead of

        
  /// "all-in-one.bundle.js" we need to tell that the wasm module files can be loaded from CDN (jsdelivr).

        
  $typst.setCompilerInitOptions({

        
    getModule: () =>

        
      'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm',

        
  });

        
  $typst.setRendererInitOptions({

        
    getModule: () =>

        
      'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm',

        
  });

        
  

        
  console.log($typst.svg({

        
    mainContent: 'Hello, typst!',

        
  }));

        
</script>

See a simple and heavily-documented previewer to learn a more practical example of usage, which watches user input and compiles the content into SVG for preview.


        
<!doctype html>

        
<html lang="en">

        
  <head>

        
    <meta charset="UTF-8" />

        
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        
    <title>Tiny Typst Previewer Example</title>

        
    <!-- Loads the full bundle or the lite version from jsdelivr -->

        
    <!-- src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-all-in-one.ts@0.6.0/dist/esm/index.js" -->

        
    <script

        
      type="module"

        
      src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-all-in-one.ts/dist/esm/contrib/all-in-one-lite.bundle.js"

        
      id="typst"

        
    ></script>

        
  </head>

        
  <body>

        
    <!-- Provides a button to export to PDF after finish editing -->

        
    <button id="export">Export To PDF</button>

        
    <!-- Accepts user input using a text area element -->

        
    <textarea id="input">Hello, Typst!</textarea>

        
    <div id="content"></div>

        
    <script>

        
      const input = document.getElementById('input');

        
      const contentDiv = document.getElementById('content');

        
      

        
      // Exports SVG and puts it into the `contentDiv`

        
      const previewSvg = mainContent => {

        
        $typst.svg({ mainContent }).then(svg => {

        
          console.log(`rendered! SvgElement { len: ${svg.length} }`);

        
          // append svg text

        
          contentDiv.innerHTML = svg;

        
          

        
          const svgElem = contentDiv.firstElementChild;

        
          const width = Number.parseFloat(svgElem.getAttribute('width'));

        
          const height = Number.parseFloat(svgElem.getAttribute('height'));

        
          const cw = document.body.clientWidth - 40;

        
          svgElem.setAttribute('width', cw);

        
          svgElem.setAttribute('height', (height * cw) / width);

        
        });

        
      };

        
      

        
      // Exports PDF and downloads it

        
      const exportPdf = mainContent =>

        
        $typst.pdf({ mainContent }).then(pdfData => {

        
          var pdfFile = new Blob([pdfData], { type: 'application/pdf' });

        
          

        
          // Creates element with <a> tag

        
          const link = document.createElement('a');

        
          // Sets file content in the object URL

        
          link.href = URL.createObjectURL(pdfFile);

        
          // Sets file name

        
          link.target = '_blank';

        
          // Triggers a click event to <a> tag to save file.

        
          link.click();

        
          URL.revokeObjectURL(link.href);

        
        });

        
        

        
      /// Listens the 'load' event to initialize after loaded the bundle file from CDN (jsdelivr).

        
      document.getElementById('typst').addEventListener('load', function () {

        
        /// Initializes the Typst compiler and renderer. Since we use "all-in-one-lite.bundle.js" instead of

        
        /// "all-in-one.bundle.js" we need to tell that the wasm module files can be loaded from CDN (jsdelivr).

        
        $typst.setCompilerInitOptions({

        
          getModule: () =>

        
            'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm',

        
        });

        
        $typst.setRendererInitOptions({

        
          getModule: () =>

        
            'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm',

        
        });

        
        

        
        /// Binds exportPdf action to the button

        
        document.getElementById('export').onclick = () => exportPdf(input.value);

        
        /// Binds previewSvg action to the textarea

        
        input.oninput = () => {

        
          previewSvg(input.value);

        
          input.style.height = '5px';

        
          input.style.height = input.scrollHeight + 'px';

        
        };

        
        /// Triggers the first preview.

        
        previewSvg(input.value);

        
      });

        
    </script>

        
    <style>

        
      body {

        
        margin: 0px;

        
        display: flex;

        
        flex-direction: column;

        
        align-items: center;

        
      }

        
      #export {

        
        width: 100%;

        
        height: 20px;

        
      }

        
      #input {

        
        width: 100%;

        
        margin: 0;

        
        padding: 0;

        
        border-width: 0;

        
        height: auto;

        
      }

        
    </style>

        
  </body>

        
</html>

        


        
<!doctype html>

        
<html lang="en">

        
  <head>

        
    <meta charset="UTF-8" />

        
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        
    <title>Tiny Typst Previewer Example</title>

        
    <!-- Loads the full bundle or the lite version from jsdelivr -->

        
    <!-- src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-all-in-one.ts@0.6.0/dist/esm/index.js" -->

        
    <script

        
      type="module"

        
      src="https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-all-in-one.ts/dist/esm/contrib/all-in-one-lite.bundle.js"

        
      id="typst"

        
    ></script>

        
  </head>

        
  <body>

        
    <!-- Provides a button to export to PDF after finish editing -->

        
    <button id="export">Export To PDF</button>

        
    <!-- Accepts user input using a text area element -->

        
    <textarea id="input">Hello, Typst!</textarea>

        
    <div id="content"></div>

        
    <script>

        
      const input = document.getElementById('input');

        
      const contentDiv = document.getElementById('content');

        
      

        
      // Exports SVG and puts it into the `contentDiv`

        
      const previewSvg = mainContent => {

        
        $typst.svg({ mainContent }).then(svg => {

        
          console.log(`rendered! SvgElement { len: ${svg.length} }`);

        
          // append svg text

        
          contentDiv.innerHTML = svg;

        
          

        
          const svgElem = contentDiv.firstElementChild;

        
          const width = Number.parseFloat(svgElem.getAttribute('width'));

        
          const height = Number.parseFloat(svgElem.getAttribute('height'));

        
          const cw = document.body.clientWidth - 40;

        
          svgElem.setAttribute('width', cw);

        
          svgElem.setAttribute('height', (height * cw) / width);

        
        });

        
      };

        
      

        
      // Exports PDF and downloads it

        
      const exportPdf = mainContent =>

        
        $typst.pdf({ mainContent }).then(pdfData => {

        
          var pdfFile = new Blob([pdfData], { type: 'application/pdf' });

        
          

        
          // Creates element with <a> tag

        
          const link = document.createElement('a');

        
          // Sets file content in the object URL

        
          link.href = URL.createObjectURL(pdfFile);

        
          // Sets file name

        
          link.target = '_blank';

        
          // Triggers a click event to <a> tag to save file.

        
          link.click();

        
          URL.revokeObjectURL(link.href);

        
        });

        
        

        
      /// Listens the 'load' event to initialize after loaded the bundle file from CDN (jsdelivr).

        
      document.getElementById('typst').addEventListener('load', function () {

        
        /// Initializes the Typst compiler and renderer. Since we use "all-in-one-lite.bundle.js" instead of

        
        /// "all-in-one.bundle.js" we need to tell that the wasm module files can be loaded from CDN (jsdelivr).

        
        $typst.setCompilerInitOptions({

        
          getModule: () =>

        
            'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm',

        
        });

        
        $typst.setRendererInitOptions({

        
          getModule: () =>

        
            'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm',

        
        });

        
        

        
        /// Binds exportPdf action to the button

        
        document.getElementById('export').onclick = () => exportPdf(input.value);

        
        /// Binds previewSvg action to the textarea

        
        input.oninput = () => {

        
          previewSvg(input.value);

        
          input.style.height = '5px';

        
          input.style.height = input.scrollHeight + 'px';

        
        };

        
        /// Triggers the first preview.

        
        previewSvg(input.value);

        
      });

        
    </script>

        
    <style>

        
      body {

        
        margin: 0px;

        
        display: flex;

        
        flex-direction: column;

        
        align-items: center;

        
      }

        
      #export {

        
        width: 100%;

        
        height: 20px;

        
      }

        
      #input {

        
        width: 100%;

        
        margin: 0;

        
        padding: 0;

        
        border-width: 0;

        
        height: auto;

        
      }

        
    </style>

        
  </body>

        
</html>

        

#

Installing by Package Managers

You can also install the library from registry, npm as an example:


        
npm install @myriaddreamin/typst.ts

        
# Optional: if you want to run a typst renderer.

        
npm install @myriaddreamin/typst-ts-renderer

        
# Optional: if you want to run a typst compiler.

        
npm install @myriaddreamin/typst-ts-web-compiler

        
npm install @myriaddreamin/typst.ts

        
# Optional: if you want to run a typst renderer.

        
npm install @myriaddreamin/typst-ts-renderer

        
# Optional: if you want to run a typst compiler.

        
npm install @myriaddreamin/typst-ts-web-compiler

Then, you can import the library in your code:


        
import { $typst } from '@myriaddreamin/typst.ts';

        
console.log((await $typst.svg({

        
  mainContent: 'Hello, typst!' })).length);

        
// :-> 7317

        
import { $typst } from '@myriaddreamin/typst.ts';

        
console.log((await $typst.svg({

        
  mainContent: 'Hello, typst!' })).length);

        
// :-> 7317

In Node.js, it reads and loads the Wasm modules from node_modules in the filesystem. If you aim to use the library in browsers, you may need to configure the library to load the wasm module files. Please check the section.

#

Using a snippet instance

As a shortcut, a global instance $typst is provided, and it will lazily initialize the compiler and renderer for you. Import the global instance like this:


        
import { $typst } from '@myriaddreamin/typst.ts';

        
import { $typst } from '@myriaddreamin/typst.ts';

A snippet instance will store some state for the sake of convenience, which makes it not suitable for concurrent usage. You can create a new instance using the class TypstSnippet:


        
import { TypstSnippet } from '@myriaddreamin/typst.ts/contrib/snippet';

        
const $typst = new TypstSnippet({

        
  // optional renderer instance

        
  renderer: enableRendering ?? (() => {

        
    return createGlobalRenderer(

        
      createTypstRenderer, initOptions);

        
  }),

        
  compiler() => {

        
    return createGlobalCompiler(createTypstCompiler,

        
      initOptions);

        
  }

        
});

        
import { TypstSnippet } from '@myriaddreamin/typst.ts/contrib/snippet';

        
const $typst = new TypstSnippet({

        
  // optional renderer instance

        
  renderer: enableRendering ?? (() => {

        
    return createGlobalRenderer(

        
      createTypstRenderer, initOptions);

        
  }),

        
  compiler() => {

        
    return createGlobalCompiler(createTypstCompiler,

        
      initOptions);

        
  }

        
});

#

Compiling APIs

You can compile a single typst code string to different formats:


        
const mainContent = 'Hello, typst!';

        
// into vector format

        
await $typst.vector({ mainContent });

        
// into svg format

        
await $typst.svg({ mainContent });

        
// into pdf format

        
await $typst.pdf({ mainContent });

        
// into canvas operations

        
await $typst.canvas(div, { mainContent });

        
const mainContent = 'Hello, typst!';

        
// into vector format

        
await $typst.vector({ mainContent });

        
// into svg format

        
await $typst.svg({ mainContent });

        
// into pdf format

        
await $typst.pdf({ mainContent });

        
// into canvas operations

        
await $typst.canvas(div, { mainContent });

You can add some extra source input files before compiling:


        
await $typst.addSource('/template.typ', templateContent);

        
await $typst.addSource('/template.typ', templateContent);

It also supports binary input files:


        
// add an image file

        
const pngData = await fetch(...).arrayBuffer();

        
$typst.mapShadow('/assets/tiger.png', new Uint8Array(pngData));

        
// add an image file

        
const pngData = await fetch(...).arrayBuffer();

        
$typst.mapShadow('/assets/tiger.png', new Uint8Array(pngData));

You can clean up shadow files for underlying access model:


        
$typst.resetShadow();

        
$typst.resetShadow();

Note: this function will also clean all files added by addSource.

#

Splitting compilation and rendering

The compilation result could be stored in an artifact in Vector Format, so that you can decouple compilation from rendering.

You can either compile the document to a vector format in browsers:


        
const vectorData = await $typst.vector({ mainContent });

        
const vectorData = await $typst.vector({ mainContent });

or load the data from remote machine, which is precompiled by some tools:


        
const remoteData = await (fetch(

        
    './main.sir.in').then(resp => resp.arrayBuffer()));

        
const vectorData = new Uint8Array(remoteData);

        
const remoteData = await (fetch(

        
    './main.sir.in').then(resp => resp.arrayBuffer()));

        
const vectorData = new Uint8Array(remoteData);

With vectorData, you can export it to different formats without compiling again:


        
// into svg format

        
await $typst.svg({ vectorData });

        
// into canvas operations

        
await $typst.canvas(div, { vectorData });

        
// into svg format

        
await $typst.svg({ vectorData });

        
// into canvas operations

        
await $typst.canvas(div, { vectorData });

In this way, the library only requires the typst-ts-renderer module for rendering.

#

Initializing using the low-level API

The extra initialization options must be at the start of the main routine, or accurately before all invocations. You can set the options by low-level or high-level APIs. The low-level APIs are direct but not easy to use:


        
// Specifies init options of renderer

        
$typst.setRendererInitOptions(rendererInitOptions);

        
// Specifies init options of compiler. For example, cache default fonts to file system

        
$typst.setCompilerInitOptions(await cachedFontInitOptions());

        


        
// The compiler instance is initialized in this call. After that, setting options makes no sense.

        
await $typst.svg({ mainContent });

        
// Specifies init options of renderer

        
$typst.setRendererInitOptions(rendererInitOptions);

        
// Specifies init options of compiler. For example, cache default fonts to file system

        
$typst.setCompilerInitOptions(await cachedFontInitOptions());

        


        
// The compiler instance is initialized in this call. After that, setting options makes no sense.

        
await $typst.svg({ mainContent });

Some examples are still easy. For instance, a commonly usage is configuring the way to obtain the wasm module files:


        
$typst.setCompilerInitOptions({

        
  getModule: () =>

        
    '/path/to/typst_ts_web_compiler_bg.wasm',

        
});

        
$typst.setRendererInitOptions({

        
  getModule: () =>

        
    '/path/to/typst_ts_renderer_bg.wasm',

        
});

        
$typst.setCompilerInitOptions({

        
  getModule: () =>

        
    '/path/to/typst_ts_web_compiler_bg.wasm',

        
});

        
$typst.setRendererInitOptions({

        
  getModule: () =>

        
    '/path/to/typst_ts_renderer_bg.wasm',

        
});

Please check the low-level components to get full reference about these options:

  • Compiler in Wasm (Web)
  • Renderer in Wasm (Web)

#

Initializing using the high-level use API

todo: fully document the use API.

  • preloadFontFromUrl
  • preloadFontData
  • preloadFonts
  • disableDefaultFontAssets
  • preloadFontAssets
  • preloadRemoteFonts
  • withPackageRegistry
  • withAccessModel
  • fetchPackageRegistry
  • fetchPackageBy

Specify address to a http server for filesystem backend (shadowed by the addSource and mapShadow api):


        
const cm = window.TypstCompileModule;

        
const fetchBackend = new cm.FetchAccessModel(

        
  'http://localhost:20810',

        
);

        
$typst.use(

        
  TypstSnippet.withAccessModel(fetchBackend),

        
);

        
const cm = window.TypstCompileModule;

        
const fetchBackend = new cm.FetchAccessModel(

        
  'http://localhost:20810',

        
);

        
$typst.use(

        
  TypstSnippet.withAccessModel(fetchBackend),

        
);

Specify a memory filesystem backend (shadowed by the addSource and mapShadow api):


        
const memoryAccessModel = new cm.MemoryAccessModel();

        
$typst.use(

        
  TypstSnippet.withAccessModel(memoryAccessModel),

        
);

        
const memoryAccessModel = new cm.MemoryAccessModel();

        
$typst.use(

        
  TypstSnippet.withAccessModel(memoryAccessModel),

        
);

Fetch package from remote registry:


        
const accessModel = cm.FetchAccessModel() or

        
  cm.MemoryAccessModel() or others;

        
$typst.use(

        
  TypstSnippet.fetchPackageRegistry(fetchBackend),

        
);

        
const accessModel = cm.FetchAccessModel() or

        
  cm.MemoryAccessModel() or others;

        
$typst.use(

        
  TypstSnippet.fetchPackageRegistry(fetchBackend),

        
);

#

(Archived) The All-in-One Js Library in v0.5.0

The most simple examples always work with snippet.mts utility library, an all-in-one library with simplified API interfaces:


        
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';

        
console.log((await $typst.svg({

        
  mainContent: 'Hello, typst!' })).length);

        
// :-> 7317

        
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';

        
console.log((await $typst.svg({

        
  mainContent: 'Hello, typst!' })).length);

        
// :-> 7317

However, it is less flexible and stable than the underlying interfaces, the TypstCompiler and TypstRenderer. If you've become more familiar with typst.ts, we recommend you rewrite your library with underlying interfaces according to example usage shown by the snippet.mts library.

Note: If your script targets to CommonJS, you should import it in CommonJS path instead of In ES Module path:


        
const { createTypstCompiler } = require(

        
  '@myriaddreamin/typst.ts/dist/cjs/compiler.cjs');

        
const { createTypstCompiler } = require(

        
  '@myriaddreamin/typst.ts/dist/cjs/compiler.cjs');

#

Examples

Here are some examples for the snippet.mts utility library.

#

Example: Use the global shared compiler instance:


        
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';

        
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';

#

Example: Create an instance of the utility class:


        
const $typst = new TypstSnippet({

        
  // optional renderer instance

        
  renderer: enableRendering ?? (() => {

        
    return createGlobalRenderer(

        
      createTypstRenderer, initOptions);

        
  }),

        
  compiler() => {

        
    return createGlobalCompiler(createTypstCompiler,

        
      initOptions);

        
  }

        
});

        
const $typst = new TypstSnippet({

        
  // optional renderer instance

        
  renderer: enableRendering ?? (() => {

        
    return createGlobalRenderer(

        
      createTypstRenderer, initOptions);

        
  }),

        
  compiler() => {

        
    return createGlobalCompiler(createTypstCompiler,

        
      initOptions);

        
  }

        
});

#

Compiling APIs

You can compile a single typst code string to different formats:


        
const mainContent = 'Hello, typst!';

        
// into vector format

        
await $typst.vector({ mainContent });

        
// into svg format

        
await $typst.svg({ mainContent });

        
// into pdf format

        
await $typst.pdf({ mainContent });

        
// into canvas operations

        
await $typst.canvas(div, { mainContent });

        
const mainContent = 'Hello, typst!';

        
// into vector format

        
await $typst.vector({ mainContent });

        
// into svg format

        
await $typst.svg({ mainContent });

        
// into pdf format

        
await $typst.pdf({ mainContent });

        
// into canvas operations

        
await $typst.canvas(div, { mainContent });

You can add some extra source input files before compiling:


        
await $typst.addSource('/template.typ', templateContent);

        
await $typst.addSource('/template.typ', templateContent);

It also supports binary input files:


        
// add an image file

        
const pngData = await fetch(...).arrayBuffer();

        
$typst.mapShadow('/assets/tiger.png', new Uint8Array(pngData));

        
// add an image file

        
const pngData = await fetch(...).arrayBuffer();

        
$typst.mapShadow('/assets/tiger.png', new Uint8Array(pngData));

You can clean up shadow files for underlying access model:


        
$typst.resetShadow();

        
$typst.resetShadow();

Note: this function will also clean all files added by addSource.

#

Example: reuse compilation result

The compilation result could be stored in an artifact in Vector Format, so that you could decouple compilation from rendering or make high-level cache compilation.


        
const vectorData = await $typst.vector({ mainContent });

        
// or load vector data from remote

        
const remoteData = await (fetch(

        
    './main.sir.in').then(resp => resp.arrayBuffer()));

        
const vectorData = new Uint8Array(remoteData);

        


        
// into svg format

        
await $typst.svg({ vectorData });

        
// into canvas operations

        
await $typst.canvas(div, { vectorData });

        
const vectorData = await $typst.vector({ mainContent });

        
// or load vector data from remote

        
const remoteData = await (fetch(

        
    './main.sir.in').then(resp => resp.arrayBuffer()));

        
const vectorData = new Uint8Array(remoteData);

        


        
// into svg format

        
await $typst.svg({ vectorData });

        
// into canvas operations

        
await $typst.canvas(div, { vectorData });

Note: the compilation is already cached by typst's comemo implicitly.

#

Specify extra init options

Ideally, you don't have to specify any options. But if necessary, the extra init options must be at the start of the main routine, or accurately before all invocations.


        
// Example: cache default fonts to file system

        
$typst.setCompilerInitOptions(await cachedFontInitOptions());

        
// specify init options to renderer

        
$typst.setRendererInitOptions(rendererInitOptions);

        


        
// The compiler instance is initialized in this call.

        
await $typst.svg({ mainContent });

        
// Example: cache default fonts to file system

        
$typst.setCompilerInitOptions(await cachedFontInitOptions());

        
// specify init options to renderer

        
$typst.setRendererInitOptions(rendererInitOptions);

        


        
// The compiler instance is initialized in this call.

        
await $typst.svg({ mainContent });

Note: There are more documentation about initialization in the Import typst.ts to your project section of Get started with Typst.ts.

#

Configure snippet by the use API

Specify address to a http server for filesystem backend (shadowed by the addSource and mapShadow api):


        
const cm = window.TypstCompileModule;

        
const fetchBackend = new cm.FetchAccessModel(

        
  'http://localhost:20810',

        
);

        
$typst.use(

        
  TypstSnippet.withAccessModel(fetchBackend),

        
);

        
const cm = window.TypstCompileModule;

        
const fetchBackend = new cm.FetchAccessModel(

        
  'http://localhost:20810',

        
);

        
$typst.use(

        
  TypstSnippet.withAccessModel(fetchBackend),

        
);

Specify a memory filesystem backend (shadowed by the addSource and mapShadow api):


        
const memoryAccessModel = new cm.MemoryAccessModel();

        
$typst.use(

        
  TypstSnippet.withAccessModel(memoryAccessModel),

        
);

        
const memoryAccessModel = new cm.MemoryAccessModel();

        
$typst.use(

        
  TypstSnippet.withAccessModel(memoryAccessModel),

        
);

Fetch package from remote registry:


        
const accessModel = cm.FetchAccessModel() or

        
  cm.MemoryAccessModel() or others;

        
$typst.use(

        
  TypstSnippet.fetchPackageRegistry(fetchBackend),

        
);

        
const accessModel = cm.FetchAccessModel() or

        
  cm.MemoryAccessModel() or others;

        
$typst.use(

        
  TypstSnippet.fetchPackageRegistry(fetchBackend),

        
);

#

Specify extra render options

See comments on source for more details.