You can use https://www.skypack.dev/, it adjusts any npm package to be used in an ESM-ready environment
For example, if you want to use a library that uses UMD (Universal Module Definition) or CJS (Common JS), you can use skypack and the module will be converted to ESM (ES Modules).
Working case
The canvas-sketch-util/random library uses CJS to import and export some modules (it use require('something')
inside), but the code is converted to ESM with that service, and can run directly in the user's browser
<script type="module">
// Use 'https://cdn.skypack.dev/' + 'npm package name' + '@version its optional'
import random from 'https://cdn.skypack.dev/canvas-sketch-util@1.10.0/random'
console.log('A random number: ', random.range(1,10))
</script>
Non-working case
The same library doesn't work if we use https://unpkg.com/, as it only distributes what is ready, and the code gives error (at the very beginning of the file there are already some require functions from CJS):
<script type="module">
import random from 'https://unpkg.com/canvas-sketch-util@1.10.0/random'
console.log('A random number: ', random.range(1,10))
</script>
Important
- It's important to use
type="module"
inside the script, jsfiddle and codePen already do that, it can work locally too.
- Each library has an export differently, you must understand how the library is being exported to be able to import it into your code. Here are some examples of different ways of importing, not all cases, you have to know which way of import is the right way.
<script type="module">
// Usually when don't have a default export
import * as libOne from 'https://cdn.skypack.dev/lib-one'
libOne.initSomething({someconf:true})
// OR
libOne(someParam1, someParam2)
// Usually when export is just one function/object
import libTwo from 'https://cdn.skypack.dev/lib-two'
libTwo(someParam1, someParam2)
// Usually when there are several things inside the lib and you only want to use one
import { libThree } from 'https://cdn.skypack.dev/lib-three'
libThree(someParam1, someParam2)
</script>
Final considerations - 2022
Their website ( https://www.skypack.dev/ ) says the following
Skypack is free to use for personal and commercial purposes, forever. The basic CDN is production-ready and is backed by Cloudflare, Google Cloud, and AWS. We're fully committed to building a core piece of infrastructure you can rely on.
So it seems to be something you can trust