@@ -142,3 +142,47 @@ const Parser = require('web-tree-sitter');
142142 console .log (tree .rootNode .toString ());
143143})();
144144```
145+
146+ #### Running .wasm in browser
147+
148+ ` web-tree-sitter ` can run in the browser, but there are some common pitfalls.
149+
150+ ##### Loading the .wasm file
151+
152+ ` web-tree-sitter ` needs to load the ` tree-sitter.wasm ` file. By default, it assumes that this file is available in the
153+ same path as the JavaScript code. Therefore, if the code is being served from ` http://localhost:3000/bundle.js ` , then
154+ the wasm file should be at ` http://localhost:3000/tree-sitter.wasm ` .
155+
156+ For server side frameworks like NextJS, this can be tricky as pages are often served from a path such as
157+ ` http://localhost:3000/_next/static/chunks/pages/index.js ` . The loader will therefore look for the wasm file at
158+ ` http://localhost:3000/_next/static/chunks/pages/tree-sitter.wasm ` . The solution is to pass a ` locateFile ` function in
159+ the ` moduleOptions ` argument to ` Parser.init() ` :
160+
161+ ``` javascript
162+ await Parser .init ({
163+ locateFile (scriptName : string , scriptDirectory : string ) {
164+ return scriptName;
165+ },
166+ });
167+ ```
168+
169+ ` locateFile ` takes in two parameters, ` scriptName ` , i.e. the wasm file name, and ` scriptDirectory ` , i.e. the directory
170+ where the loader expects the script to be. It returns the path where the loader will look for the wasm file. In the NextJS
171+ case, we want to return just the ` scriptName ` so that the loader will look at ` http://localhost:3000/tree-sitter.wasm `
172+ and not ` http://localhost:3000/_next/static/chunks/pages/tree-sitter.wasm ` .
173+
174+ ##### ` Can't resolve 'fs' in 'node_modules/web-tree-sitter' `
175+
176+ Most bundlers will notice that the ` tree-sitter.js ` file is attempting to import ` fs ` , i.e. node's file system library.
177+ Since this doesn't exist in the browser, the bundlers will get confused. For webpack you can fix this by adding the
178+ following to your webpack config:
179+
180+ ``` javascript
181+ {
182+ resolve: {
183+ fallback: {
184+ fs: false
185+ }
186+ }
187+ }
188+ ```
0 commit comments