48
头图
Great Music sound, invisible elephant, knowing too large or destruction, the more "complicated" things, the principle tends to be "simple", Road to SR, complex in the heart .

We all know that npm is a package management tool in the JavaScript world and the default package management tool of the Node.js platform. Through npm, you can 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 in . It world's largest software registry 161b812b527aa0.

Usually, we use npm install xxx to install dependencies in modern front-end projects such as React, Vue, Angular, but the front-end projects are essentially HTML, JavaScript and CSS running on the browser side, then we have a way to directly in the browser console Does npm package and use

If you are interested in this issue, you might as well follow me through this article to find out, maybe you will eventually find: more "complex", the principle tends to be "simple" .

Introduce <script /> resources through 061b812b527af0

Install the npm package in the browser console, looks like a idea 161b812b527b12, which makes people feel impractical. If I ask the question in another way: how to introduce JavaScript into the browser/HTML? Maybe you have the answer right away: the <script /> tag. That's right, our first step is to introduce cdn resources on the HTML page <script />

So, how about inserting the <script /> tag on the console page to introduce CDN resources? This question can not you 161b812b527b2c:

// 在页面中插入<script />标签
const injectScript = (url) => {
  const script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
};

We have to give users some tips after the introduction of resources and when errors occur:

script.onload = () => {
    console.log(pkg_name_origin, ' 安装成功。');
};
script.onerror = () => {
  console.log(pkg_name_origin, ' 安装失败。');
};

In this way, we can directly import cdn resources in the console, and you can add some additional processing logic for the aftermath, such as removing the <script /> tag. Of course, you can also completely by creating <link /> to introduce css style library label , but many go here.

Install the npm package according to the package name

The above has realized the <script /> resources through 061b812b527baf, but we usually install the npm package through npm install directly followed by the package name. Obviously, it <script /> alone. Then, is there a way to change Our package name is directly converted to the resource address 161b812b527bb8?

The answer is of course: yes. Otherwise I will write a fart 🤔, cdnjs provides such a capability.

cdnjs provides a simple API , allowing anyone to quickly query resources on the CDN. For specific use, readers can refer to the official link. Here is an example of querying CDN resource links based on the package name. You can open this link directly 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 is the latest CDN resource address name/function of 161b812b527c05:

jquery

Therefore, searching for the cdn resource URL based on the package name has the following implementation:

const cdnjs = async (name) => {
  const searchPromise = await fetch(
    `https://api.cdnjs.com/libraries?search=${name}`,
    // 不显示referrer的任何信息在请求头中
    { referrerPolicy: 'no-referrer' }
  );
  const { results, total } = await searchPromise.json();
  if (total === 0) {
    console.error('Sorry, ', name, ' not found, please try another keyword.');
    return;
  }

  // 取结果中最相关的一条
  const { name: exactName, latest: url } = results[0];
  if (name !== exactName) {
    // 如果名称和你传进来的不一样
    console.log(name, ' not found, import ', exactName, ' instead.');
  }
  // 通过<script />标签插入
  injectScript(url);
};

Install a specific version of the npm package

In npm, we can also npm install jquery@3.5.1 , and cdnjs can only return the detailed information of the specific version (excluding the cdn resource link).

UNPKG 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 load any file using the following URL: unpkg.com/:package@:version/:file .

For example, accessing https://unpkg.com/jquery@3.5.1 will automatically redirect to https://unpkg.com/jquery@3.5.1/dist/jquery.js and return the v3.5.1 of the jQuery file of the 061b812b527cac version (if there is no version number, the latest resource will be returned):

jquery_unpkg

In other words, we can https://unpkg.com/ package name to the <script /> label to load the resource:

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

Complete code

Simply organize the above code and call npmInstall

// 存储原始传入的名称
let pkg_name_origin = null;
const npmInstall = (originName) => {
  // Trim string
  const name = originName.trim();
  pkg_name_origin = name;
  // 三种引入方式
  // 如果是一个有效的URL,直接通过<script />标签插入
  if (/^https?:\/\//.test(name)) return injectScript(name);
  // 如果指定了版本,尝试使用unpkg加载
  if (name.indexOf('@') !== -1) return unpkg(name);
  // 否则,尝试使用cdnjs搜索
  return cdnjs(name);
};

// 在页面中插入<script />标签
const injectScript = (url) => {
  const script = document.createElement('script');
  script.src = url;
  script.onload = () => {
    console.log(pkg_name_origin, ' 安装成功。');
  };
  script.onerror = () => {
    console.log(pkg_name_origin, ' 安装失败。');
  };
  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}`,
    // 不显示referrer的任何信息在请求头中
    { referrerPolicy: 'no-referrer' }
  );
  const { results, total } = await searchPromise.json();
  if (total === 0) {
    console.error('Sorry, ', name, ' not found, please try another keyword.');
    return;
  }

  // 取结果中最相关的一条
  const { name: exactName, latest: url } = results[0];
  if (name !== exactName) {
    console.log(name, ' not found, import ', exactName, ' instead.');
  }
  // 通过<script />标签插入
  injectScript(url);
};

We can use npmInstall('moment') to call on the console:

console

The following calling methods are naturally also supported:

npmInstall('jquery'); // 直接引入
npmInstall('jquery@2'); // 指定版本
npmInstall('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'); // cdn地址

Doesn't it work not to write these functions every time

After reading the above operation, it is indeed very simple, but maybe you will say: Every time I want to use it, I have to define and call functions in the console, which is a bit troublesome. not write these functions every time? That's natural, you can write a browser plug-in , and inject these JS codes into the page. For details, please refer to Learn to write a browser plug-in in 7 minutes—breaking the restriction that SDN is not logged in to prohibit copying .

If you really do not want to write, in fact, someone has written for you, and that is Console Importer , it can make your browser more powerful console become a testing ground .

  • Example of use:

import

  • Effect picture:

Console Importer

Link: Console Importer | Chrome plug-in address

What can be done

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

Normal development, we often want to try some of the projects in operation in some libraries or verification methods, print the results , through the study of this article, later you can be introduced directly in the console loadsh、moment、jQuery、React etc. to use and verification, reduce The frequency of deletion after verification console.log in the project.

  • You can easily perform DOM operations in some projects and pages jQuery
  • You can make some simple interface requests axios
  • You can verify the use of some time formatting methods moment.js
  • You can loadsh and calling its method;
  • ...

What can be learned

unpkg

unpkg is a front-end commonly used global fast CDN whose content is derived from npm. 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. Figure. The usage method is generally unpkg.com/:package@:version/:file . Or more concisely: https://unpkg.com/ package name, when the package name includes the version number, you will get the js file of the corresponding version, if it does not include the version number, you will get the latest version of the js file of this library.

cdnjs

cdnjs is a free and open source CDN service, trusted by more than 12.5% of websites, processing more than 200 billion requests per month, and supported by Cloudflare. It is similar to Google CDN and Microsoft CDN services, but the speed is faster than the two. CDNJS provides many JavaScript libraries. You can directly quote 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 API https://api.cdnjs.com/libraries?search=xxx to look up the specific library 161b812b528010, this API will also some alternatives to the library you are querying .

From the avenue to the simplicity, the complexity is in the hearts of the people

The more "complex" things, the more "simple" the principle may be. simple, and the complexity is in the hearts of people . I wish every hard-working climber will eventually become clear and relieved.

Reference

This article was first published on personal blog , welcome to and star .


獨釣寒江雪
3.2k 声望12.1k 粉丝

👑 Nothing is given, Everything is earned!