Skip to content

binding_web: replace dynamic require with import#4304

Merged
amaanq merged 1 commit intotree-sitter:masterfrom
tmr232:no-dynamic-require
Apr 19, 2025
Merged

binding_web: replace dynamic require with import#4304
amaanq merged 1 commit intotree-sitter:masterfrom
tmr232:no-dynamic-require

Conversation

@tmr232
Copy link
Contributor

@tmr232 tmr232 commented Mar 22, 2025

Dynamic require is not allowed inside ES modules.
As a result, loading web-tree-sitter was partially broken when loaded
using import, causing calls to Language.load(...) to fail.

The require call was replaced with import, making it work both
as a ES module and as a CJS module.

This seems to be most easily demonstrated by trying to run web-tree-sitter under vitest when installing it from npm.
It fails when using import { Parser, Language } from "web-tree-sitter", but succeeds with const { Language, Parser } = require("web-tree-sitter").
My test to reproduce this was minimal - just Language.load(...).

After after making the change in this PR, I ran the tree-sitter tests, as well as trying to run my minimal test with both import methods (ESM and CJS), and it worked ok.
That said, this is my first foray into the JS/TS build-pipeline shenanigans, and I don't feel confident enough to say it doesn't break other usecases.

Dynamic `require` is not allowed inside ES modules.
As a result, loading `web-tree-sitter` was partially broken when loaded
using `import`, causing calls to `Language.load(...)` to fail.

The `require` call was replaced with `import`, making it work both
as a ES module and as a CJS module.
@tmr232 tmr232 marked this pull request as ready for review March 22, 2025 19:22
Copy link

@HerringtonDarkholme HerringtonDarkholme left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks! this looks good!

@amaanq
Copy link
Member

amaanq commented Apr 19, 2025

thanks!

@amaanq amaanq merged commit 27fa108 into tree-sitter:master Apr 19, 2025
14 checks passed
@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.

web-tree-sitter uses a dynamic require inside an ES module

4 participants