[js_interop] Allow module-scoped exports for top level members #55029
Labels
area-web
Use area-web for Dart web related issues, including the DDC and dart2js compilers and JS interop.
web-js-interop
Issues that impact all js interop
Problem
There is currently no way to export a function or class to the module scope, rather than the global scope. Module-scoped functions and classes are the defacto ways of sharing code between modules, and slight tweaks to the compilation process would enable js interop within multiple environments beyond the Browser.
Description
I'm working on a node_interop experiment using the latest Dart
js_interop
library. Though Dart has generally only been concerned with running Dart in browser environments and as the primary client, I've been pleasantly surprised that it was not difficult to get Dart to run on a local machine as a module (i.e. called from another script) using Node.js, and that little work is required to enable such environment-agnostic js compilation.Part of my
node_interop
experimentation includes creating a VSCode extension using Dart. VSCode requires defining a module as entrypoint, which is expected to expose anactivate
anddeactivate
function. I've managed to get a Dart VSCode extension working by defining the following entrypoint script that calls into the generated dart code.Dart code:
This separate
package:build
issue is regarding allowing a preamble to be added to the beginning of the generated js script, while this issue targets the second half of theindex.js
script. Both solutions together would enable dart2js compilation to multiple environment targets without a separate main script.A related problem is that the ergonomics around defining a top level function are quite poor. Dart currently requires defining three separate functions: a setter to set the function using
allowInterop
, the actual implementation (activateImplementation
above), and (optionally) the Dart-callable exported function declaration.Proposed Solution
There are two separate problems with their own proposed solutions:
module
object available in Node.JS runtimes, via amodule
getter, similar toglobalThis
Using a new
@JSModuleExport
annotation, the above Dart code would be reduced by 50% to the following:or alternatively using extension types:
Note the following improvements:
index.js
export-extraction scriptmain()
function requirement - the existence of an @export annotation should imply an entrypoint to the compilersThe text was updated successfully, but these errors were encountered: