How to import NPM package in JSFiddle?
Asked Answered
H

3

27

I would like to use valid-url to validate some URLs using JSFiddle so that I can share it later. I tried adding a link to the index.js file from Github (https://raw.githubusercontent.com/ogt/valid-url/master/index.js) but Fiddle says:

Github is not a CDN, using it as such will cause issues with loading the file. Do you still with to it?

And obviously when I try to use it, an error is thrown:

Refused to execute script from [...] because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

So, is there any way to use npm packages in a JSFiddle? Or any workaround to achieve this?

Humo answered 20/10, 2017 at 8:30 Comment(1)
You can't use code directly from GitHub, but you can include them from rawgit.com. Also, using RequireJS is probably a good idea because you won't be able to use the normal require(...) or import ... syntax on the web.Fluviomarine
F
33

Use unpkg.com. They allow you to load any npm module from the browser like a CDN.

Franko answered 18/1, 2018 at 1:3 Comment(0)
G
14

Using UNPKG you can load any file from any package following this pattern

https://unpkg.com/:package@:version/:file

So, if you add

https://unpkg.com/[email protected]/

Then you'll get this (as shown in the next image)

UNPKG npm package in JSFiddle

If you specify the index.js file

https://unpkg.com/[email protected]/index.js

Then you'll get this (as shown in the next image)

JSFiddle with npm packages

You'll then be able to use it in your fiddles by adding the Resources you want to.

Gradatim answered 22/9, 2020 at 9:18 Comment(0)
C
4

If you want to import something from npm on the frontend, you can use https://www.skypack.dev/ which converts npm modules to ES Modules, example:

<script type="module">
  // Use 'https://cdn.skypack.dev/' + 'npm package name' + '@version its optional'
  import random from 'https://cdn.skypack.dev/[email protected]/random'

  console.log('A random number: ', random.range(1,10))
</script>

Here's a JSFiddle using SkyDev to load an npm module.

There are many cases that https://unpkg.com/ wouldn't handle that https://www.skypack.dev/ can, so I recommend using it whenever it's on the front-end

I wrote a slightly more complete answer here about this: How can I use a CommonJS module on JSFiddle?

Coffelt answered 1/3, 2022 at 1:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.