Skip to content

export wasm files to better support bundling use cases#4208

Merged
amaanq merged 1 commit intotree-sitter:masterfrom
vemoo:export-wasm
Apr 19, 2025
Merged

export wasm files to better support bundling use cases#4208
amaanq merged 1 commit intotree-sitter:masterfrom
vemoo:export-wasm

Conversation

@vemoo
Copy link
Contributor

@vemoo vemoo commented Feb 16, 2025

When using a bundler, calling Parser.init() without options may not work because the file won't be where it expects it.

With esbuild for example a better way is to import the wasm file with the file loader and provide it on Parser.init:

  • index.js
import path from "node:path";
import { Parser } from "web-tree-sitter";
import TreeSitterWasmUrl from "web-tree-sitter/tree-sitter.wasm";

await Parser.init({
    locateFile: (url, scriptDir) => {
        if (url === "tree-sitter.wasm") {
            return path.join(scriptDir, TreeSitterWasmUrl);
        }
    },
});
  • build.js
import esbuild from "esbuild";

await esbuild.build({
    entryPoints: ["index.js"],
    outdir: "dist",
    bundle: true,
    platform: "node",
    format: "esm",
    loader: {
        ".wasm": "file",
    },
});

This will copy the wasm file to the output directory and replace TreeSitterWasmUrl with the relative path to it.

Unfortunately at the moment it fails with:

✘ [ERROR] Could not resolve "web-tree-sitter/tree-sitter.wasm"

    index.js:3:30:
      3 │ import TreeSitterWasmUrl from "web-tree-sitter/tree-sitter.wasm";
        ╵                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  The path "./tree-sitter.wasm" is not exported by package "web-tree-sitter":

    node_modules/web-tree-sitter/package.json:19:13:
      19 │   "exports": {
         ╵              ^

  You can mark the path "web-tree-sitter/tree-sitter.wasm" as external to exclude it from the
  bundle, which will remove this error and leave the unresolved path in the bundle.

This PR fixes it.

@amaanq
Copy link
Member

amaanq commented Apr 19, 2025

awesome, thank you for the detailed explanation!

@amaanq amaanq merged commit 4dffb81 into tree-sitter:master Apr 19, 2025
@WillLillis WillLillis added the ci:backport release-0.25 Backport label label Apr 19, 2025
@tree-sitter-ci-bot
Copy link

Successfully created backport PR for release-0.25:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants