24

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?

josemigallas
  • 3,761
  • 1
  • 29
  • 68
  • 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. – Derek 朕會功夫 Oct 20 '17 at 08:43

3 Answers3

33

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

Lance
  • 75,200
  • 93
  • 289
  • 503
12

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/valid-url@1.0.9/

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/valid-url@1.0.9/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.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
2

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/canvas-sketch-util@1.10.0/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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
KevynTD
  • 487
  • 4
  • 9