1

On a webpage, I am not using Node.js.

I wanted to use p-limit like this:

<script src="
https://cdn.jsdelivr.net/npm/[email protected]/index.min.js
"></script>

But this doesn't work.

Cannot use import statement outside a module

Naively, I tried:

<script type="module" src="
https://cdn.jsdelivr.net/npm/[email protected]/index.min.js
"></script>

Which errors out:

Failed to resolve module specifier "yocto-queue".

I eventually realized there are "commonJS" and "ES6". So I tried:

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

Which doesn't errors out until:

<script type="module">
    const l = pLimit(10);
</script>

where it says:

pLimit is not defined

Eventually, this works:

<script type="module">
import pLimit from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm'
const l = pLimit(10);
</script>

I don't understand why it needs to be in the same block. If I modify the code to remove the import/export, I can use it in <script src="changed_plimit.js"></script> (of course, I don't really want to do that).

Ultimately, I'd like to know if it can be used <script src="https://cdn..."></script>. Obviously my understanding is limited. Am I completely off?

1 Answer 1

2

This package is a pure ESM module, so it has to be imported as a module. import imports the exported contents of the file within the scope of the module where it is imported, so in your case only inside the script tag. If you really want to make it global (which you probably don't need), you can do something like:

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

Then it is available as window.pLimit or simply pLimit.

But still, if you don't need to use pLimit in multiple <script>s, you can just use the import in the same <script> tag.

Sign up to request clarification or add additional context in comments.

1 Comment

…and even if you do need it in multiple scripts, you should declare the import in each of them individually; that's what modules are all about. Don't fear, it still being loaded only once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.