NPM install, YARN add, CNPM install, etc. So have you ever wondered where all these bags come from? Don’t be confused, this article will reveal how they come about and teach you how to make your own NPM installable component library.

🔥 Whether NPM, YARN or CNPM they all have a common name: JavaScript package management tools. As the name suggests, both are used to manage packages, which users post online for ready use. And CNPM and NPM are originally of the same origin, their orders are roughly the same, but CNPM has better domestic. Yarn is different, but with a cache for offline download. Below release three eldest brother’s official website, you can go to understand, this time the theme is NPM package upload.

  • NPM: NPM
  • cnpm:npm.taobao.org/
  • Yarn: The Chinese version of yarn

🔥 create a package

git init my_npm_comp
cd my_npm_comp
npm init -y
Copy the code

To create this, you initialize a Git repository, an NPM repository (to create package.json dependencies).


🔥 2. Write a component library

Note here that we are making a component library, not a component, so we need to be as modular as possible.

We create a components folder under package.json, and the files that are created inside are your components. For example, I’m going to make an Alert component and a Toast component.

First create alert. js and toast.js under components.

❤️1. Make the Alert component

This is a component to make up the number, do not blame, in order to gather a library, or explain.

Alert.js under components:

Let Alert = {show:function(){Alert (' 666')}} export default Alert;Copy the code

❤️2. Toast component production

Toast.js under components:

let Toast = {
  // A hidden setTimeOut reference
  hideTimeOut: null./** * initializes */
  init: function () {
    var toastNode = document.createElement("section");
    toastNode.innerHTML =
      '<i class="iconfont icon-success"></i><i class="iconfont icon-error"></i><span class="text">111</span>';
    toastNode.id = "toastWaka"; // Set the id so that a page has only one Toast
    toastNode.setAttribute("class"."toast"); // Set the class name
    toastNode.style.display = "none"; // Set hidden
    document.body.appendChild(toastNode);
  },
  /** * display Toast *@param Text Indicates the text content *@param Type Type SUCCESS Error *@param Duration Duration */
  show: function (text, type, duration) {
    // Make sure that the last TimeOut is cleared
    if (this.hideTimeOut) {
      clearTimeout(this.hideTimeOut);
      this.hideTimeOut = null;
      // console.error(' The previous TimeOut has not run out! ');
      // return;
    }
    if(! text) {console.error("Text cannot be empty!");
      return;
    }
    var domToastWaka = document.getElementById("toastWaka");
    console.log("domToastWaka", domToastWaka);
    if(! domToastWaka) {console.error("The toastWaka DOM does not exist!");
      return;
    }
    var domIconSuccess = domToastWaka.querySelector(".icon-success"); // Success icon
    var domIconError = domToastWaka.querySelector(".icon-error"); // Error icon
    var domToastText = domToastWaka.querySelector(".text"); / / text
    domToastText.innerHTML = text || "";
    switch (type) {
      case "success":
        domIconSuccess.style.display = "inline";
        domIconError.style.display = "none";
        break;
      case "error":
        domIconSuccess.style.display = "none";
        domIconError.style.display = "inline";
        break;
      default:
        domIconSuccess.style.display = "none";
        domIconError.style.display = "none";
        break;
    }
    domToastWaka.style.display = "block";
    // The default value is 2s
    var that = this;
    this.hideTimeOut = setTimeout(function () {
      domToastWaka.style.display = "none";
      that.hideTimeOut = null; // set TimeOut reference to null
    }, duration || 2000);
  },
  /** * hidden Toast */
  hide: function () {
    // If TimeOut exists
    if (this.hideTimeOut) {
      // Clear the TimeOut reference
      clearTimeout(this.hideTimeOut);
      this.hideTimeOut = null;
    }
    var domToastWaka = document.getElementById("toastWaka");
    if (domToastWaka) {
      domToastWaka.style.display = "none"; }}}; Toast.init();export default Toast;
Copy the code

❤️3. CSS styles and library export export

My_npm_comp create style. CSS to put CSS styles, index.js is the entire component library exit, easy to install after importing components.

style.css

Toast / * * /
#toastWaka {
    position: absolute;
    display: none;
    left: 50%;
    bottom: 50%;
    z-index: 99999;
    margin: 0 auto;
    -webkit-transform: translate(-50%);
    transform: translate(-50%);
    width: 120px;
    height:40px;
    line-height: 40px;
    border-radius: 5px;
    text-align: center;
    color: #fff;
    background-color: rgba(000.000.000.0.5);
}
 
#toastWaka .text{
    color: #fff;
    display: inline-block;
    font-size: 14px;
    position: absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
}
Copy the code

It’s important to note that index.js must have an export before you can import it. Here involves some front-end modular knowledge, will be supplemented later, interested partners can also go to view.

index.js

import Toast from './components/Toast'
import Alert from './components/Alert'


let myLibs = {}

myLibs.Alert = Alert
myLibs.Toast = Toast

export default myLibs
Copy the code

🔥 3. Upload the component library

❤ ️1. Switch the NPM source to NPM

npm config set registry=http://registry.npmjs.org
Copy the code

❤️2. Register an NPM account

Existing accounts can be skipped.

First go to NPMJS official website to register an account, be sure to email verification.

Official website: NPM

You can also register using the NPM command: see below

Bash terminal registration account:

npm adduser
Copy the code

Enter your account password as prompted. Tip: If you type the password, the characters will not be displayed. If you do not verify the account, you cannot verify the push package.

❤️3. Log in

The login account can be skipped. (Use the command NPM whoami to view.)

Creating an account using a command automatically logs in. You can manually create one on the official website as follows:

npm login
Copy the code

I will use the account Huqinggui to demonstrate.

❤️4. Release (push) packages

npm publish
Copy the code

From the terminal, the package is published successfully. We open our NPMJS to see if the package exists.

Lol, isn’t that the package we released?

Tip: If the package fails to be pushed, there may be a package with the same name. Please change the name in package.json and publish it again. ❤️ NPM publish publish ❤️_ Paper Plane blog -CSDN blog

If you publish an error after modifying the package, you need to modify version in package.json, which is equivalent to publishing a new version. For example, the first commit of 1.0.0 => 1.0.1, the second can be published.


🔥 4. Use component libraries

❤️1. NPM install Component library

npm i my_npm_comp
Copy the code

The package has been installed and we are going to introduce it.

❤️2. Use the component library

Use vue as an example. Note that since we are using a component library made from native JS, it can be used in any scenario. Of course, you can also use vue or React as a component library.

App.vue

<template>
  <div id="app">
      <button @click="openAlert()">Open the Alert.</button>
      <button @click="openToast()">Open the Toast</button>
  </div>
</template>
Copy the code
<script> 
import myLibs from 'my_npm_comp'
import 'my_npm_comp/style.css'
export default {
  name: "App".components: {},
  data() {
    return{}; },methods: {
    openAlert(){
      myLibs.Alert.show();
    },
    openToast(){
      myLibs.Toast.show("I am toast!"."success".3000); }}}; </script>Copy the code

Let’s demonstrate:

It works perfectly. A complete library of components was created. Component libraries are not limited to using native JS. Friends can try again by themselves, you can also do a set of common methods to upload, with access to use, very comfortable.

🔥 🔥

Wechat pay successful callback how half?

Package. json

The execution of macro and micro tasks is amazing!

It’s amazing how much more efficient front-end development can be!

NPM 解 决 方 法

How do I solve front-end asynchronous? What is asynchronous?