es-module-shims icon indicating copy to clipboard operation
es-module-shims copied to clipboard

Fix hot reloading for virtual files

Open guybedford opened this issue 6 months ago • 0 comments

I've been using a virtual filesystem in the new JSPM Sandbox with:

      self.esmsInitOptions = {
        onpolyfill:() => {},
        hotReload: true,
        source:(url, fetchOpts, parentUrl, defaultSourceHook) => {
          if (!url.startsWith('file:///virtual-pkg/')) return defaultSourceHook(url, fetchOpts, parent);
          const versionQueryParam = url.match(/\\?v=\\d+$/);
          if (versionQueryParam) url = url.slice(0, -versionQueryParam[0].length);
          let source = window.parent.jspmFileSystem[url.slice('file:///virtual-pkg/'.length)];
          if (!source) throw new Error(\`Virtual module \${url} not found, imported from \${parent}\`);
          source += '\\n//# sourceURL=about:blank\\n';
          switch (url.slice(url.lastIndexOf('.') + 1)) {
            case 'mjs': case 'js': return { type: 'js', source };
            case 'wasm': return { type: 'wasm', source };
            case 'css': return { type: 'css', source };
            case 'json': return { type: 'json', source };
            case 'tsm': case 'ts': return { type: 'ts', source };
          }
        },
        onerror:e=>window.parent.jspmSandboxError(e.message || e, '', '', '', e)
      };

where the file system is loaded virtually through the source hook.

This works great, and even supports CSS hot reloading, but the JS hot reloading on the virtual file system scheme file:///virtual-pkg/foo.js doesn't seem to reload properly.

It would be great to get some proper tests together for the virtual sandboxing use cases further to ensure this works.

guybedford avatar Jun 30 '25 13:06 guybedford