javascriptes6-modulesp-limit

p-limit - Javascript modules ES6


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

I wanted to use p-limit like this:

<script src="
https://cdn.jsdelivr.net/npm/p-limit@6.2.0/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/p-limit@6.2.0/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/p-limit@6.2.0/+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/p-limit@6.2.0/+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?


Solution

  • 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/p-limit@6.2.0/+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.