josemigallas
josemigallas

Reputation: 3909

How to import NPM package in JSFiddle?

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?

Upvotes: 27

Views: 21873

Answers (3)

KevynTD
KevynTD

Reputation: 682

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?

Upvotes: 4

Tiago Peres
Tiago Peres

Reputation: 15451

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.

Upvotes: 14

Lance Pollard
Lance Pollard

Reputation: 79258

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

Upvotes: 33

Related Questions