Publish an NPM package from 0 to 1 author: @tiffanysbear

Recently, I have encountered some problems in the project business. Some common methods or encapsulated modules need to be used in PC, WAP and even APP. However, for business PC, WAP and APP, they are often in different businesses and different code bases. However, the common encapsulation in the general direction of each big business still cannot meet the needs.

For example, a method for calculating the size of a document type may exist in the common of each business at the same time, let’s say in three code bases; If the need at this time is to modify the document type or size method, add a document type or reduce a document type, then do we need to modify the above three methods together? This is not good for code maintenance, wastes manpower, and increases the code workload.

So how do you manage the basic module code for some common dependencies? In this case, it is a good idea to encapsulate and distribute an NPM package for unified management.

Here is a simple NPM package and github address that I released as I wrote this article, following the steps below:

NPM package: Page -performance-monitor Github address: Page -performance-monitor, welcome star, issue

Next, let’s start with 0, how to publish an NPM package from 0 to 1. What is NPM ~

npm

NPM is the package management tool of the JavaScript world and is the default package management tool for the Node.js platform. NPM allows you to install, share, distribute code, and manage project dependencies.

The website address

For example, there are some very common common methods, abstract encapsulation, eliminate some redundant business requirements, can be encapsulated in a NPM package, provided to the corresponding multiple businesses to use.

So let’s enumerate a simple encapsulation step;

Publishing steps

Take the page performance monitoring tool Performance listed in my previous blog as an example. For the specific performance introduction, you can click the link and do a simple package to meet the basic business requirements of dot statistics. Later on, we will talk about how to package a high-quality NPM package, such as adding some examples, testing test, improving readme.md, etc., and gradually improve it. The steps are as follows:

2. Prepare package.json. 3. Register NPM account and log in

The process of delivering a good quality NPM package often depends on the code to be encapsulated, single test coverage of the code, demo cases, README introduction, etc

Project preparation:

The steps to get started, starting with a basic project creation, are done on a Linux Mac environment:

// Create a new project folder mkdir page-performance // initialize NPM, initialize package.json NPM init // Prepare the package code // put the source code in SRC, // We can add the code we need to SRC // suppose we only need to publish an index.js //......Copy the code

Publish a simple NPM package:

1, first go to the official website to register an account, fill in the account, password, email 2, then login to the NPM account NPM login, if your company has its own default NPM warehouse or use taobao image, pay attention to specify the warehouse address; npm login –registry=https://registry.npmjs.org

# will ask you to enter your username, password, and email in turn
Username:  
Password:
Email: (this IS public) 
Copy the code

3, publish a package NPM publish – registry=https://registry.npmjs.org

It will prompt + [email protected] your package name and version, and the instructions will be released.

I ran into two minor problems while Posting, for the record, if you have the same problem, you can use the following solution: 1). “Publish Failed PUT 403” is displayed

you must verify your email before publishing a new package: www.npmjs.com/email-edit : page-performance-monitor

The email you logged in before needs to be verified. Just go to the registered email box and find the email sent by NPM. Click to verify.

2) You do not have permission to publish “page-performance”. Are You logged in as the correct user? : page-performance

You do not have permission to publish this package. The reason is that your package name is duplicate and you need to change the package name in package.json.

Here, a simple NPM package is encapsulated, how to confirm their own package is confirmed? Go to the official website search box, enter your bag name search, find yours is OK ~

At this point, you will be releasing a simple NPM package, which is sufficient if only a small requirement is fulfilled. However, if you want to publish a good quality logo with various small labels, then you need to take the following steps to optimize.

Optimize the NPM package:

1. Code environment dependence – Online and offline environment

If the project uses different configurations online and offline, you can distinguish between debug mode and production mode by the command input.

process.env.NODE_ENV === 'production'

In the corresponding package.json configuration, you need to add NPM run build –mode production to distinguish it.

2. Configure package compilation

A good NPM package often needs different output modes, such as iife mode, which is conducive to script tags, or amd, CMD and other packaging methods for export; Or you need to escape with Babel and add a polyfill; Or if you need to add demo and output different samples for demo, both need to be compiled using the configuration package.

At present common package compile tools webPack, rollup, FIS, GULp and other tools, I believe also very familiar with; Because mine is a simple tool to check the performance of a page, it is packaged and compiled using a simple rollup that is suitable for the package type of the utility.

The rollup.config.js configuration is as follows:

/**
 * @file: rollup.config.js
 * @author: Tiffany
 */
// Rollup plugins
import resolve from 'rollup-plugin-node-resolve';
import commonjs from '@baidu/rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify-es';
export default [
    {
        input: 'src/index.js',
        output: {
            file: 'dist/index.js',
            format: 'umd',
            name: 'Perf',
            legacy: true,
            strict: false.sourceMap: true
        },
        plugins: [
            resolve(),
            commonjs(),
            babel({
                runtimeHelpers: true,
                exclude: 'node_modules/**'
            }),
            uglify()
        ]
    }
];

Copy the code

The configuration with Babel is as follows:

{
    "presets": [["latest",
            {
                "es2015": {
                    "modules": false}}]],"plugins": [
        "external-helpers"]}Copy the code

Then, according to your own needs, you can choose the format format mode to produce the results you need. You can also configure according to your own project requirements, size, etc.

3. Add single test

There are many front-end single test libraries, so I won’t go into them here; In this case, mocha + Chai assertion library is used, because this library is run in the browser side, need to rely on JSDOM window object, because JSDOM library is used to implement the DOM object and global variable window added, the following is the specific configuration:

// test/index.test.js

/**
 * @file: index.test.js
 * @author: zhoufang04
 * @description: mocha + chai test
 */

const expect = require('chai').expect;
const {JSDOM} = require('jsdom');
const perf = require('.. /dist/index.js'); const {window} = new JSDOM(`<! DOCTYPE html> <html> <head> <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the minimum - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
        <meta name="author" content="test">
        <title>performance test</title>
    </head>
    <body>
        <div id="values"></div>
        <div id="app"></div>
    </body>
    </html>`);

global.window = window;

describe('Page Performance Tests'.function () {
    it('Load completed return data as object'.function () {
        expect(perf.getPerformanceTiming()).to.be.an('object');
    });
    it('Return time'.function () {
        expect(perf.getPerformanceTiming().duration).to.be.an('number');
    });
    it('Return TTFB time'.function () {
        expect(perf.getPerformanceTiming().ttfb).to.be.an('number');
    });
    it('Return requestTime time'.function () {
        expect(perf.getPerformanceTiming().requestTime).to.be.an('number');
    });
});


Copy the code

Run node. /node_modules/mocha/bin/mocha and it looks like this:

Note that if the local node version is too old, mocha may report errors. In this case, use NVM to upgrade the node version and run it again.

4. Add Example

Add the example folder, where you can use the package to add some Demo cases, so that others can better know how to use the library.

5. Improve readme.md

Add readme. md to the project file to provide the usage method, demo, matters needing attention and other information, which is convenient for others to use and easier for people to understand.

You can see the readme.md I wrote here in the page- Performance -monitor library by clicking on the link

conclusion

The above steps are how to encapsulate an NPM package from 0 to 1, which can encapsulate a simple package suitable for rapid business development, or encapsulate a high quality package to use together; Can choose according to their own business needs, time cost and so on.