Home > Software design >  How do I use a Javascript library locally without a server?
How do I use a Javascript library locally without a server?

Time:07-29

I am trying to use the following library, which extracts names from colors:

The problem is that they have a Javascript CDN, but they don't tell you how to use it unless you're using Node.

import namedColors from 'color-name-list';

let someColor = namedColors.find(color => color.hex === '#ffffff');
console.log(someColor.name); // => white

let someNamedColor = namedColors.find(color => color.name === 'Eigengrau')
console.log(someColor.hex); // => #16161d

I don't use node or a server so import doesn't work, how do I run this locally?

CodePudding user response:

One place it's hosted is on unpkg, which doesn't have cross-origin restrictions, so you may fetch from the endpoint listed in the docs:

fetch('https://unpkg.com/[email protected]/dist/colornames.json')
  .then(r => r.json())
  .then((result) => {
    console.log(result[0].name);
    // put code here that depends on the library
  })
  // .catch(handleErrors);

The library also has its own API, which can be used:

fetch('https://api.color.pizza/v1/')
  .then(r => r.json())
  .then((result) => {
    console.log(result.colors[0].name);
    // put code here that depends on the library
  })
  // .catch(handleErrors);

  • Related