Simple and complicated: what is the operation of installing NPM package on browser console?

Time:2022-8-3

Great music has the faintest notes, great form Is beyond shape is invisible, wise as fool, clever as clumsy. The more “complex” things are, the more “simple” the principle is,The road is simple and numerous

   as we all know, NPM is a package management tool in the JavaScript world, and it is node JS platform’s default package management tool. NPM allows you to install, share, distribute code, and manage project dependencies. Although NPM, as a command-line tool, has gradually declined in recent years, NPM, as a widely used repository, is still at its peakThe world’s largest software registry

  usually, we passnpm install xxxInstall dependencies in modern front-end projects such as react, Vue, angular, etc., but the front-end projects are still running HTML, JavaScript and CSS on the browser side in essence. Then, we have a wayInstall NPM package directly on browser console and useIs it?

   if you are interested in this problem, you might as well follow me to explore it through this article. Maybe eventually you will find:The more “complex” things are, the more “simple” their principles are

adopt<script />Introducing CDN resources

   install NPM package on browser console,It seems like a wild idea, which makes people feel less practical. If I ask another way: how to introduce JavaScript into browser /html? Maybe you have the answer right away:<script />label. Yes, our first step is to pass<script />Tags introduce CDN resources on HTML pages.

   then, if you insert on the page in the console<script />Tag to introduce CDN resources?This problem is not difficult for you

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

We also have to give users some tips after resource introduction and when errors occur:

script.onload = () => {
    console. Log (pkg_name_origin, 'installation succeeded');
};
script.onerror = () => {
  console. Log (pkg_name_origin, 'installation failed');
};

   in this way, we can directly introduce CDN resources into the console. You can add some additional processing logic for aftermath work, such as<script />Label removal. Of course, you are completelyYou can create<link />Tag to introduce CSS Style Library, there is no more detail here.

Install NPM package according to package name

   the above achieved through<script />CDN resources are introduced, but we usually install NPM packages throughnpm installIt is directly followed by the package name. Obviously, it depends on the package name alone<script />The way is difficult to achieve our expectations, then, is there a way to put ourThe package name is directly converted to the CDN resource addressAnd?

  of course, the answer is: Yes. Or I’ll write a fart,cdnjsIt provides such capability.

  cdnjsProvides a simpleAPI, allowing anyone to quickly query resources on CDN. Readers can refer to the official link for specific use. Here is an example of querying the CDN resource link according to the package name. 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 a page similar to the following. The first item of the array isThe latest CDN resource address of the resource with the closest name / function

Simple and complicated: what is the operation of installing NPM package on browser console?

Therefore, searching the CDN resource URL according to the package name has the following implementation:

const cdnjs = async (name) => {
  const searchPromise = await fetch(
    `https://api.cdnjs.com/libraries?search=${name}`,
    //Do not display any information of 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 what you passed in
    console.log(name, ' not found, import ', exactName, ' instead.');
  }
  //Insert through <script / > tag
  injectScript(url);
};

Install a specific version of NPM package

   we can also use similar methods in NPMnpm install [email protected]The syntax of installs a specific version of the NPM package, while cdnjs can only return the details of a specific version (excluding CDN resource links).

  UNPKGIt can help us a lot at this time. Unpkg is a fast global content distribution network for all content on NPM. Use it to quickly and easily get from any package using the following URLLoad any fileunpkg.com/:[email protected]:version/:file

  for example, visithttps://unpkg.com/[email protected]Will automatically redirect tohttps://unpkg.com/[email protected]/dist/jquery.js, and returnv3.5.1VersionjQueryFile content (if there is no version number, the latest resource will be returned):

Simple and complicated: what is the operation of installing NPM package on browser console?

   that is, we canhttps://unpkg.com/Package nameThrow it directly to<script />Tag to load resources:

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

Complete code

   simply sort out the above code and adopt a unified entry methodnpmInstallCall:

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

//Insert <script / > tags in the page
const injectScript = (url) => {
  const script = document.createElement('script');
  script.src = url;
  script.onload = () => {
    console. Log (pkg_name_origin, 'installation succeeded');
  };
  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 of 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) {
    console.log(name, ' not found, import ', exactName, ' instead.');
  }
  //Insert through <script / > tag
  injectScript(url);
};

  we can use similarnpmInstall('moment')Method is called on the console:

Simple and complicated: what is the operation of installing NPM package on browser console?

The following invocation methods are naturally supported:

npmInstall('jquery'); //  Direct introduction
npmInstall(' [email protected] '); //  Specify version
npmInstall(' https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js '); //  CDN address

No, can you write these functions every time

   looking at the above operation, it is really simple, but you may say: every time I want to use it, I have to define and call functions on the console, which is a little troublesome,No, can you write these functions every time? Naturally, you can write one by yourselfBrowser plug-in, inject these JS codes into the page. For details, please refer toLearn to write a browser plug-in in 7 minutes — break through the limitation of not logging in and not copying on an Sdn

   if you really don’t want to write, in fact, someone has written it for you, it isConsole Importer, it canMake your browser console a more powerful experimental field

  • Use example:

Simple and complicated: what is the operation of installing NPM package on browser console?

  • design sketch:

Simple and complicated: what is the operation of installing NPM package on browser console?

Link:Console Importer | Chrome plugin address

What can I do

So, what is the use of the methods and tools introduced in this article?

   in normal development, we oftenWant to try some operations or verify some library methods and print results in the project, through the study of this article, you can directly introduce it on the console in the futureloadsh、moment、jQuery、ReactAnd so on, so as to reduce the use and verification in the projectconsole.logFrequency of deletion after verification.

  • You can introducejQueryConvenient DOM operations in some projects and pages;
  • You can introduceaxiosMake some simple interface requests;
  • You can introducemoment.jsTo verify the use of some time formatting methods;
  • You can introduceloadshAnd call its method to complete some convenient calculations;

What can be learned

unpkg

  unpkgIt is a front-end from NPM, which is commonly used as a global fast CDN. It can provide access to any package and any file in a fast, concise and elegant way. It can often be seen in popular class libraries and framework documents. The general way of use isunpkg.com/:[email protected]:version/:file。 Or more succinctly:https://unpkg.com/Package name, when the package name contains the version number, you will get the JS file of the corresponding version; when it does not contain the version number, you will get the latest version of the JS file of this library.

cdnjs

  cdnjsIt is a free open source CDN service, trusted by more than 12.5% of websites, and handles more than 200billion requests per month, supported by cloudflare. It is similar to Google CDN and Microsoft CDN services, but faster than the two. Cdnjs provides many JavaScript libraries. You can directly reference these JS files on the web page to achieve the best speed experience for users to browse the website.

   you can also use its query APIhttps://api.cdnjs.com/libraries?search=xxxconductSearch of CDN address of specific library, this API will also give youReturn some substitutes of the library you queried

The road is simple and numerous

    the more “complex” things are, the more “simple” the principle may be,The road is simple and numerous, I wish every climber who tries hard to climb will be suddenly enlightened and relieved.

reference material

  this article was first published inPersonal blog, welcomeCorrection and star