dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.06k stars 1.56k forks source link

How should I load JS libraries from within WASM? #55806

Open nex3 opened 3 months ago

nex3 commented 3 months ago

(Potentially related to https://github.com/dart-lang/sdk/issues/55733)

Currently, it's unclear what the "well-paved road" is for loading JavaScript libraries within a WASM context. For built-in JS APIs, it's easy: I use dart:js_interop to define the shape of the JS API I want to use and tell Dart what its global name is, and then it gets wired up for me in the generated mjs wrapper. But what if I want to access a name that's not globally available in every context?

Any global name I write via dart:js_interop gets translated in the mjs wrapper to globalThis.<name>. But adding values to this isn't very ergonomic; for example, you can't write:

import * as lib from 'library';
globalThis.lib = lib;
import {instantiate, invoke} from './myapp.mjs';

myapp.mjs won't see globalThis.lib. You'd have to put that assignment in a third library in order for it to work. Is that really the expected pattern here? Or should there be a better way?

srujzs commented 3 months ago

Would importing libraries via the dynamic import make this easier? You can define an interface for the resulting JSObject module.

nex3 commented 3 months ago

Asynchronous loads are not feasible in this case.

medz commented 1 month ago

We urgently need an unsafe static definition of methods such as' import xxx from xxx 'and' export xxx '. When I learned about the implementation of dynamic pouring, it seemed that it was very easy for Dart SDK to implement it.

With true top attribute access, we can use Dart to develop any content that complies with CJS or ESM.