I wrote a tool kit for converting Chinese into pinyin, called Pinyin-Pro, which supports pinyin, initials, vowels, tones and other conversion forms for Chinese characters, words, sentences and other formats.

Two days ago, I went to NPM and searched using pinyin keywords, only to find my package at the bottom of the second page. I looked at many packages in front of me, but the downloads and popularity are not as good as mine. Is this reasonable?

A careful study, it was found that the principle of the NPM package search rankings also have a statement. Even some of the best open source packages like React and Vue don’t pay much attention to this.

Do you think I can live with that? NPM package ranking rules and optimization of NPM package detailed tutorial.

NPM package ranking indicator

First you search for any package, and if there is a package name that exactly matches your search, it will be the number one NPM search. So, like search engines, NPM’s priority weight must be the match between the package name and what you’re searching for, and the weight is much higher than other metrics.

In the picture below, I randomly search for an ADSA, and the first package that appears is its exact match, although the package is not of good quality and no one has access to it.

The NPM package has three indicators, namely P (Popularity), Q (Quality), and M (Maintenance), in addition to name matching similarity.

According tohttps://api.npms.io/v2/package/:packageNameThis interface is used to query NPM package information, which contains the score of the package indicator.

Popularity

Popularity is the most difficult one to optimize. It is mainly related to the number of downloads and Popularity of your bag, and promotion of Popularity depends on your promotion (of course, the features of your bag need to be good enough).

It contains the following four indicators:

  • CommunityInterest is the sum of your Git’s star + Watch + fork. (After several days of summary and practice, I finally found this rule)
  • This one is a little confusing, so I did a closer look at it, and it’s close to monthly downloads, but a little less than the monthly downloads shown on NPM.
  • DownloadsAcceleration: This is related to the acceleration of the number of downloads, and the details are not clear, but don’t worry too much about optimizing your package.
  • DependentsCount: The NPM community depends on the number of your package, i.e. how many other NPM package dependecies use your package.

Quality

Quality is related to your NPM package code specifications, tests, specifications, etc., and represents the Quality of your NPM package, which will be the focus of our optimizations in this article.

It also contains four indicators:

  • Carefulness: How careful you are with your bag. This includes whether your package includes readme, gitignore, LICENSE, code specification Lint, etc.
  • tests: package.jsonDo you have the test script in it and your test case coverage?
  • Health: Package. json information is complete, including whether description, keywords and other information have TODO.
  • branding: README.mdTags at the beginning of the document in, for examplenpm version,downloadsThose.

Maintenance

Maintenance is about how often you do it, so you can improve your rating by maintaining it regularly.

Similarly, Maintenance has four metrics:

  • ReleasesFrequency: As the name implies, the frequency of NPM releases.
  • CommitsFrequency: commitsFrequency of github commit.
  • OpenIssues: indicates the number of open issues on Github
  • IssuesDistribution: not clear

Before optimization

This is the status of my package before optimization. You can see that the index score of Q (Quality) on the right side is very low. Through the search of pinyin keywords, the ranking is about 20.

Through the API. NPMS. IO/v2 / package /… Query the details and directly pull to the end of the data, it can be seen that the score of quality is 0.8179011286168503, resulting in the final score of 0.6355458339200173. (Full scale of 1)

If we look closely at quality, we can see that the scores of carefulness, tests and branding are all low. Then we have the direction of optimization.

{
    "evaluation": {"quality": {"carefulness":0.7899999999999999."tests":0.6."health":1."branding":0
        },
        "popularity": {"communityInterest":289."downloadsCount":331."downloadsAcceleration":2.3441590563165904."dependentsCount":1
        },
        "maintenance": {"releasesFrequency":1."commitsFrequency":0.9078356164383562."openIssues":1."issuesDistribution":1}},"score": {"final":0.6355458339200173."detail": {"quality":0.8179011286168503."popularity":0.11479715693618153."maintenance":0.9999899725922818}}}Copy the code

The optimization process

From the above score, we have determined the direction of the optimization process mainly for the quality item.

To improve the test

NPM packages usually need to write test cases. Common test tools are Mocha, Jest, etc. I’m using Mocha here, so I’ll take Mocha as an example.

  1. To install the tools, I’m using Mocha + Chai + Istanbul. Mocha is used to write test cases, the CHAI assertion library throws an exception when it decides that the expected value is not equal to the actual value, and Istanbul is used to help us check test coverage.

    npm i mocha chai istanbul -D
    Copy the code
  2. Create a test folder in the root directory and write test cases in it. The specific test cases of Mocha are relatively simple. If you have not been exposed to them, you can simply learn them online. Take mine:

    // /test/dist.test.js
    const { pinyin } = require('.. /dist/index');
    const expect = require('chai').expect;
    
    describe('aggregate'.() = > {
      it('test1'.() = > {
        const result = pinyin(Hanyu Pinyin, { pattern: 'num'.toneType: 'num' });
        expect(result).to.be.equal('4 3 1 1');
      });
    
      // ...
    });
    Copy the code
  3. Add test commands to package.json:

    {/ /... "scripts": {+ "test": "mocha",
    + "coverage": "istanbul cover _mocha -- -R spec --timeout 15000 --recursive",
    + "coverage:check": "istanbul check-coverage",
    + "cover": "istanbul cover --report=html node_modules/mocha/bin/_mocha -- -R spec test/*.js"} / /... }Copy the code

    Run the NPM run test on the terminal to view test case coverage. Run the NPM run cover command to generate a folder named Coverage in the root directory of the project. Open the /coverage/ HTML file to view test coverage in the browser. (The other two commands will be useful later)

  4. Improve test coverage. In the next step, the browser opens the /coverage/ HTML file and finds the test coverage file that is less than 100%. Click there to see the code that is not covered by the test.

    The red and yellow sections are code not covered by test cases, which can be added to increase test coverage to 100%.

So that’s the part about improving test.

Improve the carefulness

Increase the CI

Common open source projects use Travis – CI for CI.

  1. Log in to Travis -ci and select the Github account to log in.

  2. Click the + sign in the image below to select the Github repository to add the NPM package you want to publish.

  3. Add the.travis. Yml file to the project root directory and add the following code:

    language: node_js
    node_js:
      - stable
    script: npm run test
    Copy the code
  4. When github submits, it executes the CI process and executes the test command. When the CI passes, it generates a building like this: passing brand:

    Click on the brand and select MarkDown to generate its MarkDown address and place it in your readme.md file:

To increase coverage

As mentioned earlier, test coverage is also related to NPM’s detection mechanism. Here we use the Coveralls platform.

  1. Log in to Coveralls using your Github account and select the warehouse to open:

  2. Click the DETAILS button and it will have rePO_token in it:

  3. Run the following command to install related packages: Install Coveralls

    npm i coveralls -D
    Copy the code

    Install Travis

    gem install travis
    Copy the code

    Run encrypt to replace your_rePO_token below with rePO_token in step 2 above:

    travis encrypt COVERALLS_TOKEN=your_repo_token --add
    Copy the code

    After execution, the following information is added to the.travis. Yml file, which will upload our test coverage to Coveralls, associated with NPM

    + env:
    + global:
    + secure: U8Zd1z5E3/ovD87OpBWxMm0xCNcl1mqOM+cWKgTmOJlTPVHLCVA7G9oZd8i1K7trW6fDvTJT1GW5ZNzBOV8+bYEVUeTeqAvtgiqZLLVC2IEdmfXsumvsprC8 OuCKHh8d7lNhn1vCGXGGLllO2J3tG66ATjQ2ZgdqPBUQ20mafqy4OOGkqs7PcvV1A7OMQnFNpPL6bptpxiumCdHUSirsM48e0dFRPNVfxPVYbKitil0Q+sWU h+Heb=
    Copy the code

    Add the following execution to.travis. Yml:

    + after_script: npm run cover && cat coverage/lcov.info | node_modules/coveralls/bin/coveralls.js
    Copy the code

    The complete.travis. Yml is as follows:

    language: node_js
    node_js:
      - stable
    script: npm run test
    after_script: npm run cover && cat coverage/lcov.info | node_modules/coveralls/bin/coveralls.js
    env:
      global:
        secure: U8Zd1z5E3/ovD87OpBWxMm0xCNcl1mqOM+cWKgTmOJlTPVHLCVA7G9oZd8i1K7trW6fDvTJT1GW5ZNzBOV8+bYEVUeTeqAvtgiqZLLVC2IEdmfXsumvsprC8 OuCKHh8d7lNhn1vCGXGGLllO2J3tG66ATjQ2ZgdqPBUQ20mafqy4OOGkqs7PcvV1A7OMQnFNpPL6bptpxiumCdHUSirsM48e0dFRPNVfxPVYbKitil0Q+sWU h+Heb=
    Copy the code
  4. After pushing the code on Github, you can see the test coverage in Coveralls:

    Click EMBED to copy MAEKDOWN to your EMBEDREADME.mdIn, the coverage icon will be added:

Increase eslint

  1. Install eslint
    npm i eslint -D
    Copy the code
  2. Add it to the project root directory.eslintrcFile, here the code specification can be written according to their own needs, I added the simplest:
    {
      "env": {
        "browser": true."node": true."commonjs": true
      },
      "parserOptions": {
        "ecmaVersion": 7."sourceType": "module"}}Copy the code
  3. inpackage.jsonAdd the lint command to the file, executenpm run lintCode can be tested for specification:
    {/ /... "scripts": { // ...+ "lint": "eslint ."} / /... }Copy the code

Increase the CHANGELOG. Md

Create a new changelog. md file in the root directory of the project and add your package update log. If it already exists, please ignore it.

Increase gitignore.

If the. Gitignore file does not exist in the project, create it in the project root directory. If it exists, ignore it.

Increase npmignore.

If the. Npmignore file does not exist in the project, create a new one in the project root directory. If it does exist, ignore it.

Increase the LICENSE

If there is a LICENSE, skip this step. I use another warehouse as an example to describe how to add a LICENSE.

  1. On Github, select Add File -> Create New File

  2. After entering a LICENSE file in filename, the Choose a LICENSE template option is displayed on the right:

  3. Click on the left to select a LICENSE, then click Review and Submit

  4. Finally, click Commit New File to add:

To improve the health

Health Most people have a package of 1. If not, check whether the configuration items of package.json, such as desciption, keywords, name, and main, are correct and complete.

To improve the branding

Branding is your package.json. Build and coverage have been added in the tutorial above.

Other ICONS can be viewed in shields. IO. For example, to add an NPM version icon, just add the following to the readme.md file:

[![NPM version](https://img.shields.io/npm/v/pinyin-pro.svg)](https://www.npmjs.com/package/pinyin-pro)
Copy the code

The optimized

After the above steps, our optimization process is basically about the same, let’s take a look at the optimized results, search pinyin keywords:

It can be seen that the item Q (Quality) has been greatly improved, and the ranking of the search results has directly reached the first place.

Take a look at the scores:

{
    "evaluation": {
        "quality": {
            "carefulness": 0.9999999999999999."tests": 1."health": 1."branding": 0.6
        },
        "popularity": {
            "communityInterest": 298."downloadsCount": 668.6666666666666."downloadsAcceleration": 10.897393455098936."dependentsCount": 1
        },
        "maintenance": {
            "releasesFrequency": 1."commitsFrequency": 1."openIssues": 1."issuesDistribution": 1}},"score": {
        "final": 0.69251706704311."detail": {
            "quality": 0.9995248552319843."popularity": 0.12188460135289936."maintenance": 1}}}Copy the code

It can be seen that “Test” in “quality” gets a full mark, “Carefulness” approaches a full mark, and “Branding” gets a 0.6 mark. The total score of quality in score is close to full score.

The rest of the optimization is to improve the functionality of your package, plus promotion and publicity!

The last

Finally, attach the address of my package, there is a need for Chinese characters to pinyin, and obtain initials, finals, tones of friends can download and try, feel pretty easy to use! If you feel good, you can click a star, and you are welcome to add me at the end of readme if you want to participate in building and communicating with us.

  • github: pinyin-pro
  • npm: pinyin-pro