Write a NPM package for use on the browser side

Source: Internet
Author: User

This article has been published by the author Wu Weiwei authorized NetEase Cloud community.

Welcome to NetEase Cloud Community, learn more about NetEase Technology product operation experience.


When writing a program, there is always some code that we don't want to write over and over again, such as some UI or interactive similar components, or some similar process or logic. In the past, in the face of this situation, I will be able to reuse the parts abstracted out, made reusable modules, placed in a folder dedicated to public modules, easy to find and reference. However, this can only solve the problem of reusing common modules in a single project, and if your module needs to be reused by multiple projects, then you need to find another method. This article discusses the considerations for implementing a module reuse by releasing the NPM package.


Create a new package

Execute the following command under the project root directory to initialize the Package.json file.


$ NPM Init

The meanings of the fields in the file can refer to the official documentation. One of the things to note is:


    • NAME Specifies the package name, and the package name cannot be duplicated with the existing package name when the package is published. You can see if the package name already exists by using NPM info packagename before publishing.

    • Main specifies the file that is loaded by default when the package is loaded.

    • Files specifies the file that needs to be published when the package is published. In general,. Git, node_modules, test and other files should not be published to the NPM repository.

    • dependencies specifies the third-party package that needs to be relied upon. These third-party packages are also installed at the same time when the package is installed. In order to increase the installation speed of the package, unnecessary dependencies should not be placed in the dependencies.


Packaged
Why you need to pack

During the packaging of a business project, some processes filter third-party packages, such as Babel, in order to improve packaging speed. and the ability to handle certain features in third-party libraries may not be available in business projects, such as Coffeescript used in third-party packages. Therefore, as a third-party package that can be reused well, it needs to compile and package its own source code before release.


Precautions

You can select Webpack for packaging. In the packaging process, unlike business projects:

Configure Output.librarytarget as Commonjs

The packaged files in a business project need to be executed only, and there is no need to export variables externally. In order to be able to export variables externally with the COMMONJS specification, you need to configure Output.librarytarget to COMMONJS Click to see how to configure

Filtering third-party packages when packaging

As a NPM package, you may rely on some third-party packages, such as react. If packaged directly, the packaged file will contain react code. Business projects that generally rely on this NPM package will also rely on react, so the final react code will be packaged two times. It is recommended that third-party packages are filtered at the time of packaging and that third-party packages used are declared in dependencies so that dependent third-party packages are packaged with the Business Project. Click to see how to filter third party packages

Using Babel-plugin-transform-runtime

We usually use Babel to compile the code. In the process of compiling, Babel will inject some extra code, so that the compiled code has better compatibility, such as inheritance, Promise, Map, set and other functions of the implementation. To prevent these extra code from being added repeatedly, you can use the Babel-plugin-transform-runtime plug-in at compile time to import these additional features from a third-party package (Babel-runtime) instead of adding the implementation code directly. At the same time, the babel-runtime is also filtered to make the Babel-runtime packaged with the business items. Click to see how to use Transform-runtime


Load on Demand

Sometimes a NPM package provides a lot of functionality, and a business project that relies on it requires only a fraction of it. At this point, the NPM package needs to provide a load-on-demand feature that will only package the referenced parts of the module when packaged, reducing the size of the packaged file.

Use of Babel-plugin-import

The Babel-plugin-import plug-in can implement on-demand loading capabilities.


{"Plugins": [["Import", {"LibraryName": "abc", "Style": true}]]}

The above code is part of the Babel configuration file, declaring the ability to use on-demand loading for the ABC module. It compiles the following piece of code:


Import var1 from module, VAR2, VAR3 3 variables, use only Var1import {var1, var2, var3} from ' abc ' Console.log (var1)

Compilation Result:


Import {style as _style} from ' Abc/lib/var1/style ', import _default from ' Abc/lib/var1 '; Console.log (_default);

Before compiling, import the entire ABC package. After compiling, only the used var1 are imported. Babel-plugin-import supports more flexible configurations, click to view details. Click to see how to configure Babel


In order for Babel-plugin-import to load our NPM packages on demand, there are some configurations that need to be made when packaging. such as the above ABC package, need to var1, VAR2, VAR3 and other modules are packaged separately. So after the packaging of the document in addition to Abc/index.js, but also need to have abc/lib/var1/index.js, abc/lib/var1/style.js, etc.


Test

For a common module, the most important thing should be its stability. A common module that can bring new bugs to each upgrade is not what we want. The utility module provides a small change in functionality compared to a business project, so unit testing comes into play. Imagine that the iterative process for a common module is this:


  • Define the functionality provided by the module and write test cases for these functions.

  • For functional development, pass test cases.

  • If you need to fix bugs or new features, write test cases for bugs or features through use cases.

    How to make a unit test assertion Library

    The assertion library is primarily used to compare data to determine whether it matches expectations. An exception is thrown for assertions that do not meet expectations.

    Assert.equal (' A ', ' B ')

    as the assertion above throws an exception Assertionerror: ' a ' = = ' B ' assertion library recommended use Chai , supporting multiple styles of assertions.

    Test framework

    The test framework can classify the test cases. Each test case is executed in a separate closure, and if an exception is caught in the closure, the test case is considered not to have passed.


A taxonomy describe (' type1: ', function () {//a use case (via) It (' Cases 1: ', function () {assert.equal (' a ', ' a ')}) One use case (failed) it (' Cases 2: ', function () {assert.equal (' a ', ' B ')})})

The test framework recommends the use of mocha


Test Actuator

It is recommended to use Karma, which can integrate Webpack, mocha, Chai, browser, package the test code, execute the test case in the browser environment, and finally output the results in the console.


Document

A common module should have an API document, but the cost of manually maintaining a document is too high. Fortunately, there are tools that can automatically generate API documentation based on comments in the code, and all you need to do is add code comments based on the specification. Click the view comment specification to generate a document in the form of a Web page markdown form of document


NetEase Cloud Free Experience Pavilion, 0 cost experience 20+ Cloud products!

More NetEase technology, products, operating experience sharing please click.


Related articles:
"Recommended" line of code to fix Dubbo interface calls
"Recommended" HBase principle – all the details of region segmentation are here.

Write a NPM package for use on the browser side

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.