And upload it to a third party package assembly npm

A, npm Profile

npm is built on nodejs of a package management tool for managing third-party modules. When you have installed nodejs, you can use the command npm.

There are a lot of scaffolding third-party modules, such as nodejs tool (webpack, rollup, etc.), nodejs module (mysql, path, etc.), vue and react like (vue-cli, create-react-app, etc.) on the official npm server, and js frame corresponding to numerous major components, plug-ins. Up to now (2020, February 15), on npm server has uploaded a total of more than 1.2 million third-party modules.

Overall, npm JavaScript module is a centralized management platform, almost all third-party modules related to js can be found here. Once upload your own modules to npm, it would be tantamount to open it to all of the JavaScript developer.

Speaking npm, I have to mention cnpm.

In China, many people will use cnpm command to install third-party npm package on the server, because the download speed cnpm than npm fast. So cnpm what is it?

The original, npm server is located abroad, the speed of our country npm direct access to the server is relatively slow, and sometimes there will be the installation fails. To solve this problem, Taobao team of engineers in the country also set up a server, known as the "Taobao npm Mirror" (in fact, the third party on the npm server synchronization over packet for developers to download). Taobao npm mirror server address is https://registry.npm.taobao.org, cnpm can be installed with the following command:

npm install -g cnpm -registry=https://registry.npm.taobao.org

Now you have installed cnpm, you can use the command to cnpm on Taobao server to download third-party modules from npm synchronized from the server.

Note : The server every 10 minutes and npm official server synchronization once. So if you have just uploaded a module to npm server, use the command cnpm not be able to download immediately.

Supplement : Now there is a common package management tools: yarn. Because there are some flaws in older versions of npm, such as npm installslow installed, version management disunity, Facebook, Google and other Internet companies jointly launched a new package management tool yarn. Compared to npm, it is faster and better performance, much of the Internet giant welcome. As the yarn and npm principle is basically the same, here we will not go into details, interested can go to find out.

Second, upload a vue component to npm

Here we upload a vue component as an example to explain the whole process of uploading third-party modules to npm server.

To upload herein is a small component of vue I wrote: vue-image-container.

It is a draggable floating window, built a number grid, you can drag some pictures on the page to go temporarily stored, and can then be dragged out of the picture is placed to the target position (currently just completed a concept version, function is not perfect, we will further improve the follow-up). Figure:
Here Insert Picture Description
When you need to put a drag images into the current viewing area outside (for example, from the top of the page you will drag a picture in the end part, and the page is very long), or when you move from one page to the route need to drag another page a picture in the past (one-page application routing switch will not cross the page, so in theory can be cross-routing drag images), you may need a component of.

Well, after a brief introduction to the components you want to upload, the following is the focus of this article: how to upload this component to npm server. It is divided into two parts, one is to complete the development component, uploaded to npm modules must follow a certain format, and the second is to upload the module to npm.

First look at the components of development:

1. Create a project vue

We first create a project using vue vue-cli (Of course, before that you need to install nodejs and vue-cli, their installation is not the focus of this article). Open cmd command in the current folder window, type the following command:

vue create vue-image-container

The default configuration selected items, ENTER to proceed. After the execution is completed, there will be a just initialized empty vue project under the current folder: vue-image-container.

Since the new version of vue-cli deleted the default configuration file, so we create a new vue.config.js under the project, when the project is structured as follows:
Here Insert Picture Description

2. Configure vue.config.js

Next we want to configure the look of the project configuration file, as follows:

module.exports = {
      pages: {
        index: {
          entry: 'src/main.js,
          template: 'public/index.html,
          filename: 'index.html
        }
      },
      css: {
        extract: false   //强制使用内联样式,这样打包出的插件样式会内置在js中,不需要单独引入
      }
    }

Here is the standard vue.config.js configuration.

pages parameter specifies the entry js files and HTML project template to use.

css extract attribute parameter specifies whether to generate during packaging separate style file. If the extract is set to true, then the project will generate a separate package css file, you must introduce the css file at the same time when it can be introduced, such as:
Here Insert Picture Description
When your component has multiple themes, doing so would be more flexible. But if your component is only a style, you can set the parameter to false, then all styles will be packaged into inline styles, developers do not need to use the time to introduce a separate style file. Here we provide only a topic for the time being, so the extract is set to false.

3. New packages folder

In general, we will write local components in the src directory, and then call in other components. But now we need to be prepared to upload to third-party components npm, we do not want it and the other code project mix (this is not conducive pack), so we will create a new folder to store packages this component.

At this time, items following structure:
Here Insert Picture Description

4. Writing Plugins

We first develop a good component in the manner of conventional development component, which is no different from writing directly in the src plug-ins:
Here Insert Picture Description

<template>
  ...  // 模板
</template>

<script>
  ...  // 脚本代码
</script>

<style>
  ...  // 样式
</style>

Note : We not only can upload a single component to npm, you can also upload a component library, then the following packages may contain more vue components.

After the development of plug-in packagesunder the new directory index.jsas a file entry component.
Here Insert Picture Description

(1) a single component development

If only a single component to upload (e.g., of the project), index.js code is as follows:

// 导入组件
import imgContainer from './img-container/img-container'; 

let plugin = {};
plugin.install = function( Vue ){
    Vue.component(imgContainer.name, imgContainer); // 注册组件
}

// 当使用Vue.use(plugin)安装插件时,
// 实际上就是在调用这里暴露出的对象的
// install方法,因此务必确保这里带有install方法
export default plugin;    

Components of the index file exposes a plugin object that has a installmethod, when calling Vue.use()the installation components, in fact, call this method. So you can use such as the following imgContainer:

Local Project:

// 引入组件暴露出的plugin对象
import imgContainer from 'img-container';

// 执行plugin的install方法
Vue.use(imgContainer);  

Note that even if the components are not downloaded from npm, you can also call Vue.use(), as long as the object has passed install method.

(2). Development Component Library

If you want to upload a component library, you can write something like the following index.js:

import ... from ''
import ... from '';
...   // 将所有的组件引入进来

const components = [...]; // 将上述组件保存到一个数组

// 定义install方法,它将作为export暴露的对象的方法被Vue.use调用
const install = function(Vue){
	// 判断当前组件是否已被安装过,如果已安装过则不再安装
    if(install.installed) return;  
    install.installed = true;
    
    // 遍历components数组,依次注册每个组件
    components.map(component => {
        Vue.component(component.name, component);
    }) 
}

if(typeof window !== 'undefined' && window.Vue){
    install(window.Vue);
}
export default{
    install,
    ...components    //将插件暴露出去,这样可以按需引入
} 
// 如果只需要部分组件,请使用import {button} from '';
// Vue.component(Button)的语法手动注册组件
// 这样便可以实现按需引入

Introducing component library project in a manner consistent with the introduction of a single component.

5. Component Testing

After you finish writing assembly, you need to be tested in order to exclude uploaded to the server after npm bug components. We are still in a conventional manner, in srcthe preparation of the project code folder, the introduction of packagesthe following components of the test (we sometimes put srcthe folder change test, said it was testing components used).
Here Insert Picture Description
App.vue:
Here Insert Picture Description
with the introduction of the components of conventional way is the same, but the path is packagesthe folder.

6. Configure package.json

This step is to prepare for the testing and packaging, we add the following code at the top of the original package.json:
package.json:

  "name": "vue-image-container",  // 组件名
  "version": "0.1.4",  // 版本号
  "description": "img-container",  // 组件描述
  "main": "lib/vue-img-container.umd.min",  // 打包结果文件
  "private": false,   // 是否为私有项目
  "author": "carter_liu",
  "license": "MIT",
  "style": "lib/vue-img-container.css",  // 打包后的样式文件
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "lib": "vue-cli-service build --target lib --name vue-img-container --dest lib packages/index.js"  // 打包命令
  },
  // 下面的配置都是自动生成的,不用动
  "dependencies": {
    ... 
  },
  "devDependencies": {
	... 
  },
  ...

It should be particularly noted that the component you want to upload to the npm, privateparameters must be set false.

In addition, choose to generate a separate css file if the configuration vue.config.js before, then here's style argument is required (otherwise it will not find the style file), if there is no separate css file, this parameter can be omitted.

Here the most important thing is scriptsin liborder, calling it the module can be packaged, only finished package can be uploaded to the server npm. Let's analyze the meaning of the various parameters:

vue-cli-service build  // 调用vue-cli提供的build命令
--target lib // 打包目标是package.json同级目录下的lib文件夹(打包时会自动创建)
--name vue-img-container // 包名
--dest lib packages/index.js // 打包入口是packages文件夹下的index.js

7. Packaging

At the command line, type:

npm run lib

Then press Enter to be packaged components. Wait a moment, libfolder packed result will be generated. This libis what we really give developers use the package (in theory, you can only upload to npm this folder, but in most cases we will upload the entire project, other developers to facilitate learning and research).

8. .npmignore configuration file

Under the new project root directory .npmignore file:
Here Insert Picture Description
This file folder is a convention which does not require npm uploaded to the server. In general, node_modules folders, and the project file (such as .idea, .vscode), etc. are not to upload, and the lib folder is necessary to upload, the other as needed.

Here is my profile:

    node_modules/
    vue.config.js
    babel.config.js
    *.map
    *.html

    .idea
    .vscode

Above the file or folder will not be uploaded to npm.

So far, we have developed and packaged components finished, ready to be uploaded to the npm. To upload to npm, you first need to have a npm account.

9. Registration npm account

Login URL: https: //www.npmjs.com, can sign up for a free developer account. After registration you need to verify the mailbox, the mailbox is not verified can not upload module.

Tip : I use the phone to verify the end of the mailbox and found still unverified email upload, then verify the mailbox at the computer to function properly, do not know whether it was a mistake.

10. npm account login

Back to the project folder, open a command line window, type:

npm login

Then in turn need to enter a user name and password (the password is hidden, the losers can directly enter) and mailboxes.

Entry is complete, press enter to log npm account.

11. publishing component

Now we can publish components to the server npm. Excuting an order:

npm publish

Enter, wait a minute, the components will be uploaded to the server npm.

If you encounter the following error when executing the command:

403 Forbidden - PUT https://registry.npm.taobao.org/vue-image-container - [no_perms] Private mode enable, only ad
      npm ERR! 403 In most cases, you or one of your dependencies are requesting
      npm ERR! 403 a package version that is forbidden by your security policy.

This is because the mirror server Taobao (Taobao mirror server there may be some permissions issues when uploading module), you can enter the following command:

npm config set registry http://registry.npmjs.org/

Upload the server address is reset to the official address of the server, and then execute again npm loginand npm publishcan successfully uploaded.

Update on component : If you need to upgrade the components, you need to modify the version number of the project go package.json file, and then execute again npm publish. Remember, if you do not modify the version number on the package npm server is not updated.

In addition, the npm unpublish ...command module for the revocation uploaded.

Third, the summary

In this paper, a simple vue component as an example to explain how to develop and upload to a third-party components npm server. In view of the package assembly (commonly known as "create the wheel") has been known as one of a front-end developer of the most important skills, the students still have not tried it a try as soon as possible.

Published 44 original articles · won praise 98 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41694291/article/details/104328725