preface

This is an inclusive NPM release tutorial, in order to avoid a lot of articles in the sharing, follow step by step, finally failed to send a package. I’m out of time. I’m in a bad mood.

Therefore, while writing this article, I re-created an NPM package, followed the following process, released an NPM package, also available for testing, so children can rest assured to follow the step by step, learn to release NPM package.The project code for the package is here,The address of the NPM package that has been published online is here

NPM was originally a package management tool for Node.js, but with the rapid development of JS in recent years, now NPM has become almost all js related tools and software package management tool, this time will also go through the package process from 0 to 1.

1. This paper takes THE VUE project as an example to explain. The process can be used in general, but the installation of specific projects is slightly different

2. ⚠️ Tip: In order to let children understand the package delivery process and configuration, it is still recommended to operate in the sequence of steps (1) – (10). In order to highlight the whole package delivery process, the packaged test components are very simple. After understanding the contents and principles of all the files, and successfully sending out a test NPM package, children can change into their own components and publish their own NPM package, set the name of the release package to our-bTN

Initialize webPack project + component wrap === all in one go

In our projects, we all want to install plug-ins as small as possible, so we also want to control our dependencies when we ship packages, so I chose to create a package project myself instead of using cumbersome vue and React scaffolding. Words do not say, the following follow 👇

  • (1) Below is the recommended directory structure, according to the following structure to establish the project file

However, due to the simplicity of the components in this article, the assets and utils folders are deleted (the existence of these two folders does not affect the package delivery of NPM, and it is only convenient for you to organize the project code).

├─ SRC │ ├─ assets# local static resources (not available in this article)│ ├ ─ ─ the componentsBusiness Common Components│ │ ├ ─ ─ btnDemo. VueThis article needs to encapsulate a simple Button component│ ├ ─ ─ utils# Tool library (not available in this article)│ └ ─ ─ index. Js# App entry├─.npmignore // Use to ignore files that don't need to be uploaded to NPM ├─ readme.md ├─ package.json ├─ package.json ├─ webpack.config.js# webpack configuration/ / noteThe # utils folder usually houses utility functions that your component uses frequently
The # assets folder contains static assets such as styles, images, ICONS, etc
Copy the code
  • (2)The button component
// btnDemo.vue <template> <div class="btn"> <button>{{text}}</button> </div> </template> <script> export default { name: 'BTN ', // Props: {text: {// text type: String, default () { return '' } } }, data () { return { } } } </script>Copy the code
  • (3)index.js

This file is intended to expose our component

// src/index.js
// import BTN and btndemo. vue with the same name attribute.

import btn from './btnDemo.vue'

btn.install = Vue= > Vue.component(btn.name, btn) // Configure the install method for the component

export default btn;
Copy the code

⚠️ (there is a pit here) : Since the btn.name of Vue.component(btn.name, BTN) is the name attribute that points to btnDemo.vue, it is recommended to use the name attribute value of the component as the import alias here

  • (4)webpack.config.js

The configuration of webpack.config.js is as follows. Since the version we use is Webpack4, all the configuration is in webpack.config.js

This configuration is used to package the contents of/SRC into the btn.js folder in /dist (which automatically generates /dist folder when packaged). Btn.js is actually our plug-in (the main field in package.json also points to this).

// webpack.config.js
const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')

module.exports = {
  entry: {
    index: path.join(__dirname, "/src/index.js") // the entry file (the same index.js used to expose the component)
  }, 
  output: {
    path: path.join( __dirname, "/dist"), // The packaged files are stored in the dist folder
    publicPath: '/dist/'.// Set the public path
    filename: "btn.js".// Set the output file to btn.js
    libraryTarget: 'umd' // This option attempts to expose the library to the previous module-defining system, which makes it compatible with CommonJS and AMD, or exposes it as a global variable
  },
  module: {
    rules: [{test: /\.vue$/.loader: 'vue-loader'
      },
      {
        test: /\.css$/.use: ['style-loader'.'css-loader'] {},test: /\.(scss|sass)$/.use: ['style-loader'.'css-loader'.'sass-loader'] {},test: /\.(png|jpg|svg|gif)$/.use: ['url-loader'] {},test: /\.js$/.exclude: /node_modules|vue\/dist|vue-router\/|vue-loader\/|vue-hot-reload-api\//.loader: 'babel-loader'}},plugins: [
    new VueLoaderPlugin()
  ]
}
Copy the code
  • (5)package.json

The package.json field is described below. The dependencies in devDependencies are not unique. You can write them according to your own circumstances

// The specific fields are specified {"name": "our-btn"// Publish the name of the NPM package"version": "1.0.0", // Your NPM package version"description": "A test button"// Package description"main": "dist/btn.js"// * key * : Specify the main entry file for your component"scripts": {
    "build": "webpack --mode production"."dev": "webpack-dev-server --open --mode development"
  },
  "keywords": [
    "our-btn"."button"]."repository": {
    "type": "git"."url": "git+https://github.com/thomaszhou63/test-npm.git"
  },
  "author": "thomaszhou"."license": "MIT"."devDependencies": {
    "babel-core": "^ 6.26.3"."babel-loader": "^ 7.1.5." "."babel-preset-env": "^ 1.7.0"."css-loader": "^ 1.0.0"."file-loader": "^ 2.0.0." "."style-loader": "^ 0.23.1"."url-loader": "^ 1.1.2." "."node-sass": "^ 4.12.0"."sass-loader": "^ 7.2.0"."vue": "^ 2.5.2." "."vue-hot-reload-api": "^ 2.2.4." "."vue-html-loader": "^ 1"."vue-loader": "^ 15.4.2." "."vue-style-loader": "^ 3.0.3." "."vue-template-compiler": "^" 2.5.9."webpack": "^ 4.19.0"."webpack-cli": "^ 3.1.0"}}Copy the code
  • Parameters that
    • name– Package name (the package name should be kebab-case, that is, all lowercase words or underlined)
    • version– Package version number (recommended in the first version1.0.0, specific naming rulesLook here)
    • description– Description of the package. innpmjs.comTo help users filter their search.)
    • keywords– Keywords (search for your NPM package keywords on the NPM website)
    • author-Author of the bag. The format is usuallyName < your email address >Generally speaking, withvue/reactScaffolding creates projects in this format by default, which can be a Github address or custom, but is less standard
    • license– Copyright License,MITorISCOr anything, but I see a lot of bagsMIT
    • contributors– Other contributors to the pack (I didn’t write this)
    • repository– Package codeRepoInformation, includingtypeandURL.typeCan begitorsvn.URLIs the packageRepoaddress
      • I wrote it heregitThe address of the repository, where I put my component project code, so that there is a Github entry on the NPM package page
    • main– This field specifies the main entry file of the program (best to writeThe dist folderCompressed file in)
      • mainDefines the package entry file inNodeJsEnvironment, statementimport [pkg] from '[package]'Import the file defined by main
    • scripts– Specifies the NPM command line abbreviation to run the script command. Such asnpm start,npm run dev,npm run buildEtc.
    • dependencies / devDependencies– Production/development environment dependency package list. They will be installed onnode_moduledirectory
      • As a developer,dependenciesanddevDependenciesIt doesn’t really make much difference, because it’s executingnpm install/yarn addWill all download
      • dependenciesIs a dependency that must be installed to run your package, i.e. when the user isnpm install [package]oryarn add [package]These dependencies are also downloaded
      • devDependenciesAre dependencies that need to be installed when developing your package, for exampleeslint.jestSuch development tools as usersnpm install [package]oryarn add [package]These dependencies are not downloaded!

My version is 1.0.1 because I iterated on a later version myself. If you are a first version, it is better to have 1.0.0

  • (6)README.md

This is what my readme. md wrote, and it will eventually show up in the NPM content introduction. If you send a package, please write the readme. md well, after all, it is for human use

## our-btn> a test NPM package# install

​```
npm install our-btn
​```
# use
​```
// main.js
import btn from 'our-btn'

Vue.use(btn)
​```
​```
// demo.js
<template>
  <div class="demo">
    <btn :text="msg"></btn>
  </div>
</template>

<script>
export default {
  name: 'demo'.data () {
    return {
      msg: 'success'
    }
  }
}
</script>
​```
Copy the code
  • (7).npmignore

Gitignore ignores the selected files and uploads them to the Github repository, while. Npmignore ignores the selected files and uploads them to NPM.

However, if your project does not have a.npmignore file, but does have a.gitignore file, the files defined in.gitignore will be ignored when publishing. That is,.npmignore has a higher priority than.gitignore.

.*
*.md
node_modules/
webpack.config.js
src/
Copy the code
  • (8) Install dependencies

Json dependencies can be installed by running the following command, which will generate the node_modules folder and package-lock.json files in your directory

npm install
Copy the code
  • (9) Pack our components
npm run build
Copy the code
  • (10) Directory structure

Here is my directory structure, with the.gitAttributes and.gitignore files you can ignore because I put the project in the Github repository.

The local test component is available

Run the following commands in the project

npm run build / / packaging
npm pack // Generate an our-btn-1.0.1. TGZ package locally
Copy the code

Create your own vUE/React project. Since I am a VUE component, I will create a vUE project named test-bTN. We will put our-btn-1.0.1. TGZ into our local project test-bTN

npm install our-btn1.01..tgz
npm run dev // Start vUE project
Copy the code

Then import our package in the project’s main.js

// src/main.js
// Note: BTN should remain the same as the index
import btn from 'our-btn' / / into the bag

Vue.use(btn)
Copy the code

Reference this component in our demo page

// demo.vue <template> <div class="demo"> <btn :text="msg"></btn> </div> </template> <script> export default { name: 'demo' data () {return {MSG: 'success'}}} < / script >Copy the code

If the tests are available, run NPM uninstall our-bTN to uninstall the plug-in in the test project test-bTN, and then it can be published to the NPM package

Published to the NPM

  • (1) Register an NPM account

Before publishing, you have to register an NPM account, otherwise how can you upload, suggest to register an account on the official website (by the way, familiar with that website), after registering the account, we will log in locally and publish our component

Note: Because some children often use CNPM source, so must switch to NPM source, otherwise the following error will be reported

error: no_perms Private mode enable, only admin can publish this module
Copy the code

So you want to switch to the source of NPM, via NPM config set registry http://registry.npmjs.org orders

  • (2) Launch

Before sending a package, check the NPM website to see if there is a package with the same name as yours. If so, change it to another name

npm login / / NPM
// Then enter your account, password and email address
/ / when you see the console Logged in as < Username > on https://registry.npmjs.org log in successfully

// Skip the NPM run build step if you are sure it is the latest version and already packaged
npm run build 
npm publish // Publish your package (if you appear at 👇 and display +[package]@ version information, then publish successfully)
Copy the code

👇 This is my input and what it shows

🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉 At this moment your package has been published successfully!! 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉 🎉

⚠️ extension knowledge: a version can only be released once, that is, you can not send 1.0.0, the next time also 1.0.0, theoretically can be overwritten, but NPM does not allow this, because you are overwritten, there is no way to know your version information, plug-ins and projects are iterative, like git, there is version information.

Method 1: Manually change the version of package.json before every NPM publish

Method 2: Run the following command to publish information

Assuming the initial version is 1.0.0 ➜ NPM version preminor (execute this command, V1.0.0-0 ➜ NPM version prepatch v1.0.1-0 ➜ NPM version patch (execute this command to price the current package release as v1.0.1) v1.0.1Copy the code

Check out NPM && to use our package

In this case, just wait a few minutes and go to the NPM website to search for your bag name. If not, then wait, maybe the update is slow, not fully updated, but you can view your own package in your NPM account

Create a vUE/React project locally. I’m a VUE component, so I’ll create a vue project.

NPM install our- BTN // Install our packageCopy the code

Then import our package in the project’s main.js

// SRC /main.js // note: BTN should keep the same import BTN from the index'our-btn'Vue. Use (BTN)Copy the code

Reference this component in our demo page

// demo.vue
<template>
  <div class="demo">
    <btn :text="msg"></btn> 
  </div>
</template>

<script>
export default {
  name: 'demo'.data () {
    return {
      msg: 'success'
    }
  }
}
</script>
Copy the code

If the error please correct, I also correction update

If you don't understand, please leave a message. I will reply when I see it

over