Skip to content

"Cannot use import statement outside a module" error when loading playground-elements from CDN #426

@btheado

Description

@btheado

This issue might be related to #418.

The issue

Loading version 0.20 from a CDN results in "Cannot use import statement outside a module" error and the result is not rendered. Doing the same using version 0.18.1 works fine.

The lit.dev playground can be used to illustrate the issue by embedding playground-ide inside of playground-ide. Here are links showing the working and non-working versions:

The only difference between the code in the two links is this in the broken version:

<script type="module">
 import 'https://cdn.jsdelivr.net/npm/[email protected]/+esm'
</script>

and this in the working version:

<script type="module">
 import 'https://cdn.jsdelivr.net/npm/[email protected]/+esm'
</script>

My analysis of what is causing it

The change #398 added {type: 'module'} to only one of the two new Worker constructors. The one which is using a Blob to construct the script does not have the type=module. This version of worker instantiation is the one used when loading playground-elements via CDN.

When the blob version of the code is called, an error like this results:

Uncaught SyntaxError: Cannot use import statement outside a module (at 2e86fb86-0430-40ce-b5f6-dbdb42b5b8d9:1:1)

Here is the code I'm referring to. I think changing the 2nd Worker call will fix the issue:

if (typescriptWorkerScriptUrl.origin === window.location.origin) {
// Easy case.
worker = new Worker(typescriptWorkerScriptUrl, {type: 'module'});
} else {
// If the worker script is different-origin, we need to fetch it ourselves
// and create a blob URL.
const resp = await fetch(typescriptWorkerScriptUrl.href);
const text = await resp.text();
const blobUrl = URL.createObjectURL(
new Blob([text], {type: 'application/javascript'})
);
worker = new Worker(blobUrl);

However, as I noted in a later comment:

I doubt {type: 'module'} is enough to fix it since internal/typescript would likely not be available relative to the blob url and the import will fail

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions