BQN icon indicating copy to clipboard operation
BQN copied to clipboard

bqn.js: JavaScript import module support

Open jhvst opened this issue 1 year ago • 2 comments

What I want to do

import { bqn } from "./libbqn.js";

What I get instead

Uncaught SyntaxError: The requested module 'http://localhost:8000/libbqn.js' doesn't provide an export named: 'bqn'

What I expect to happen

The single function relevant for my main.js to get loaded.

Why this change

While working on WASM-based tree-sitter support for BQN code highlighting for my blog (demo here), I ran into the convoluted world of modern JavaScript imports.

In my main.js file, when I run the tsserver LSP, I get these errors saying that bqn function does not exist, because my editor is not running in a browser context. In the browser the function is defined when the file is imported via the script tag and everything works.

To make the LSP happy, what can be done instead is to use the import feature to load the functions from some URI to "lift" the context of the LSP to the similar situation as the browser. However, this requires the variable to be prefixed with export in the source file. Once done, the script tag in HTML must be updated to include type="module" if using an import statement in any other JS file.

Even with the export change, a user does not need to update their JS import unless some other file is trying to read it using JS module features. In other words, introducing this change should not cause any apparent regressions, but only add features to those wanting to use modern JS.

jhvst avatar Jul 20 '24 14:07 jhvst

My bad, it does in fact cause a regression: Uncaught SyntaxError: export declarations may only appear at top level of a module. This can be fixed by importing the file with type="module". More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/import_decl_module_top_level

Switched to draft as merging would break any online code which loads the file from the master branch on GitHub.

jhvst avatar Jul 20 '24 14:07 jhvst

Additionally, as-is, it breaks the top-level ./bqn.js node REPL too (and, more generally, including docs/bqn.js via a node require).

dzaima avatar Jul 20 '24 16:07 dzaima