Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Big sound xi sound, elephant invisible, great wisdom is like a fool, big qiao if zhuo, the more “complex” things, its principle tends to “simple”, the road to simple, complex in the heart.

As we all know, NPM is the package management tool for the JavaScript world and is the default package management tool for the Node.js platform. NPM allows you to install, share, distribute code, and manage project dependencies. Although NPM as a command-line tool has declined in recent years, NPM as a widely used repository continues to thrive and is the largest software registry in the world.

NPM install XXX usually installs dependencies in modern front-end projects like React, Vue, Angular, etc., but front-end projects are essentially HTML, JavaScript, and CSS running on the browser side. Is there a way to install the NPM package directly on the browser console and use it?

If you are interested in this question, follow me through this article and you may find that the more “complicated” something is, the more “simple” it is.

through<script />Import CDN resources

Installing the NPM package on the browser console may seem like a far-fetched idea. What if I asked the question in a different way: How do I introduce JavaScript into the browser /HTML? You may have the answer right away: the tag. Yes, our first step is to introduce CDN resources on the HTML page via the tag.

How about inserting a tag on the page at the console to bring in CDN resources? There’s no problem with this:

// Insert the  tag in the page
const injectScript = (url) = > {
  const script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
};
Copy the code

We also need to give the user some hints after the resource is introduced and when errors occur:

script.onload = () = > {
    console.log(pkg_name_origin, 'Installation successful. ');
};
script.onerror = () = > {
  console.log(pkg_name_origin, 'Installation failed. ');
};
Copy the code

This way, we can import CDN resources directly into the console, and you can add some additional handling logic for the cleanup, such as removing the tag. Of course, you can also introduce the CSS style library by creating a tag, but I won’t go into detail here.

Install the NPM package based on the package name

to introduce CDN resources, but we usually install NPM package through the NPM install directly after the package name to complete, obviously relying on the mode is difficult to achieve our expectations, then, is there a way, Can we convert our package name directly to the CDN resource address?

The answer, of course, is yes. Otherwise I write shit 🤔, CDNJS provides this capability.

CDNJS provides a simple API that allows anyone to quickly query resources on a CDN. For details, please refer to the official link. Here is an example of querying CDN resource links based on package names. You can directly open this link in the browser address bar to view: https://api.cdnjs.com/libraries?search=jquery, this is a get request, you will see something similar to the following page, first/function for the name of an array of the most similar to the latest CDN resources address:

So, search CDN resource URL according to package name can be implemented as follows:

const cdnjs = async (name) => {
  const searchPromise = await fetch(
    `https://api.cdnjs.com/libraries?search=${name}`.// Do not display any information about the referrer in the request header
    { referrerPolicy: 'no-referrer'});const { results, total } = await searchPromise.json();
  if (total === 0) {
    console.error('Sorry, ', name, ' not found, please try another keyword.');
    return;
  }

  // take the most relevant one of the results
  const { name: exactName, latest: url } = results[0];
  if(name ! == exactName) {// If the name is different from the one you passed in
    console.log(name, ' not found, import ', exactName, ' instead.');
  }
  // Insert with the  tag
  injectScript(url);
};
Copy the code

Install a specific version of the NPM package

We can also install version-specific NPM packages in NPM using syntax similar to NPM install [email protected], while CDNJS can only return version-specific details (without CDN resource links).

UNPKG can do us a great favor at this time. Unpkg is a fast global content distribution network for all content on NPM. Use it to quickly and easily load any file from any package using the following URL: unpkg.com/:package@:version/:file.

For example, accessing https://unpkg.com/[email protected] automatically redirects to https://unpkg.com/[email protected]/dist/jquery.js, And returns the contents of the jQuery file for v3.5.1 (if the version is not included, the latest resource is returned) :

That is, we can load resources by dropping the https://unpkg.com/âž• package name directly into the tag:

const unpkg = (name) = > {
  injectScript(`https://unpkg.com/${name}`);
};
Copy the code

The complete code

Simply tidy up the above code and call it through a unified entry method called npmInstall:

// Store the original passed name
let pkg_name_origin = null;
const npmInstall = (originName) = > {
  // Trim string
  const name = originName.trim();
  pkg_name_origin = name;
  // Three ways to introduce
  // If it is a valid URL, insert it directly with the  tag
  if (/^https? : \ \ / / /.test(name)) return injectScript(name);
  // If version is specified, try unpkg
  if (name.indexOf(The '@')! = = -1) return unpkg(name);
  // Otherwise, try using CDNJS search
  return cdnjs(name);
};

// Insert the  tag in the page
const injectScript = (url) = > {
  const script = document.createElement('script');
  script.src = url;
  script.onload = () = > {
    console.log(pkg_name_origin, 'Installation successful. ');
  };
  script.onerror = () = > {
    console.log(pkg_name_origin, 'Installation failed. ');
  };
  document.body.appendChild(script);
  // document.body.removeChild(script);
};

const unpkg = (name) = > {
  injectScript(`https://unpkg.com/${name}`);
};

const cdnjs = async (name) => {
  const searchPromise = await fetch(
    `https://api.cdnjs.com/libraries?search=${name}`.// Do not display any information about the referrer in the request header
    { referrerPolicy: 'no-referrer'});const { results, total } = await searchPromise.json();
  if (total === 0) {
    console.error('Sorry, ', name, ' not found, please try another keyword.');
    return;
  }

  // Take the latest result
  const { name: exactName, latest: url } = results[0];
  if(name ! == exactName) {console.log(name, ' not found, import ', exactName, ' instead.');
  }
  // Insert with the  tag
  injectScript(url);
};
Copy the code

We can make the call from the console in a manner similar to npmInstall(‘moment’) :

The following calls are naturally supported:

npmInstall('jquery'); // Direct import
npmInstall('jquery@2'); // Specify the version
npmInstall('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'); / / the CDN address
Copy the code

Why don’t you write these functions every time

It’s pretty simple, but you might say: I have to define and call functions on the console every time I want to use them, which is a bit of a hassle. Why not write them every time? You can write your own browser plug-in and inject the javascript code into the page. For details, see 7 minutes to learn how to write a browser plug-in – break the restriction of the SDN not logged in to copy.

If you really don’t want to write, someone has already written it for you, that is Console Importer, which can make your browser Console a more powerful laboratory.

  • Example:

  • Effect:

Links: the Console Importer | Chrome plug-ins address

What can be done

So, what exactly do the methods and tools described in this article do?

Loadsh, moment, jQuery, React, etc. Loadsh, moment, React, etc. Reduce the frequency of console.log verification in a project and then deletion.

  • You can do this by introducingjQueryConvenient DOM operations in some projects and pages;
  • You can do this by introducingaxiosMake some simple interface requests;
  • You can do this by introducingmoment.jsTo verify the use of some time formatting methods;
  • You can do this by introducingloadshAnd call its method to complete some convenient calculation;
  • .

What you can learn

unpkg

Unpkg is a common global fast CDN based on NPM. It can provide access to any package and any file in a fast, simple and elegant way. It is often seen in popular class libraries and framework documents. You can use unpkg.com/:package@:version/:file. Or more succinctly: https://unpkg.com/âž• package name. If the package name contains the version number, you will get the js file of the corresponding version. If the package name does not contain the version number, you will get the js file of the latest version of the library.

cdnjs

CDNJS is a free open source CDN service trusted by more than 12.5% of websites, handling more than 200 billion requests per month and powered by Cloudflare. It is similar to Google CDN and Microsoft CDN services, but faster. CDNJS provides a number of JavaScript libraries that you can reference directly on your web page to achieve the best speed of the user’s web browsing experience.

You can also pass it to specific query APIhttps://api.cdnjs.com/libraries?search=xxx library CDN address lookup, the API will give you back some substitute for the library you query.

Avenue to simple, complex in the heart

The more “complex” things, its principle may be more tend to “simple”, the road to simple, numerous in the heart, I wish every effort to climb, finally can suddenly become enlightened, relieved in the heart.

The resources

  • Console Importer

This article was first published on my blog, welcome corrections and star.

“Welcome to the discussion in the comments section. The excavation authorities will draw 100 nuggets in the comments section after project Diggnation. See the event article for details.”