playcanvas/editor

Imports of non `mjs` files fail in editor

Opened this issue · 3 comments

Code that fetches non .mjs paths do not resolve correctly in the editor.

In this example the debug.mjs is the glue script that loads the relative ./debug.wasm file. Running this files throws a network error unable to resolve ./debug.wasm.

This happens because the service worker that maps asset registry urls (./path/to/file.mjs) to the backend urls (/files/assets/api/file.mjs?id-xyz) is currently restricted to .mjs files only, meaning a fetch('./debug.wasm') will 404.

This was done to prevent any issues with fetch/import statements with existing scripts, however it's not intuitive to developers why this doesn't work.

Ideally the editor should allow a wider range or import targets, but maybe restrict the mapping to those that only originate from .mjs files

The issue with the above repro is that the bindings script is attempting to load the wasm using a relative path

fetch(new URL('debug.wasm', import.meta.url)

Currently only relative paths to es modules are resolved correctly. A quick fix for this is to use the pc.app.assets.find('debug.wasm').getFileUrl() and manually replace this url in the bindings.

I have however submitted a PR which is more permissive in resolving other types of asset urls. This means you have more ways to resolve file urls from ESM Scripts which isn't limited to importing modules

For visibility, this should allow you to do the following:

// ✅ This works
import { x }  from './my/other/module.mjs';
const { x } = import('./my/other/module.mjs');

// ✅ type attributes work
import json from '/path/to/some.json' with { type: 'json' };
import('/path/to/some.json', { with: { type: "json" } });

// ✅ relative fetch also works
fetch('/path/to/some.jpg')
fetch('/path/to/some.wasm')

Mark, would there be a ballpark week, when this fix goes out?

I'm on leave this week, but will take a look when I'm back. There's likely some impact on the project export process too