Design and Build your own JavaScript code library: Tips and tips

Source: Internet
Author: User
Code library: We are always using them. The code library is formed by developers packaging the code they will use in the project, which can save time and avoid repeated efforts. Has a reusable package, whether open source or...

Code library: We are always using them. The code library is formed by developers packaging the code they will use in the project, which can save time and avoid repeated efforts. Having a reusable package, whether open-source or closed-source, is better than repeatedly building packages with the same features or manually copying and pasting from past projects.

More articles from the author
  • Stop Maiming Bodies: The Perils of Pixel Font-Size

  • ES2016: shocould the Future of JavaScript Be Developer-Driven?

Can we more accurately describe the code library in addition to the packaged code? Except for a few, the code library is usually just a file, or several files in the same folder. Its code should be individually saved and used properly in your project. The library file allows you to adjust the structure or behavior based on different projects. Imagine a USB device that can only communicate through a USB interface. Some devices, such as the mouse and keyboard, can be configured through the interface provided by the device.

In this article, I will explain how to build library files. Although most of the methods can be applied to other languages, this article focuses on building JavaScript library files.

Why build your own Javascript library?

First and foremost, library files can be easily reused by existing code. You do not need to dig out outdated projects to copy files, but just import them into the database. This also makes your application componentized and makes the application code library smaller and easier to maintain.

Christ Church Library (source)

Any abstract code that makes it easier to implement a specific function or can be reused can be packaged into the library file. JQuery is an interesting example. Although jQuery APIs have a large number of simplified DOM APIs, it is of great significance in the past when cross-browser DOM operations were difficult.

If an open-source project becomes popular and many developers use it, it is very likely that people will participate in its development by asking questions or contributing code. In any case, it is helpful for libraries and projects dependent on it.

A popular open-source library will also bring great opportunities. The company may acknowledge the quality of your work and send you an offer. The company may ask you to integrate your project into their applications. After all, no one knows your project better than you.

Of course, it may be just a habit-to enjoy captioning, helping others and learning and growing up in this process. You can raise your limits and try new things.

Scope and target

Before writing the first line of code, you need to determine the function of your database-you need to set a goal. With this goal, you can focus on the problems you want to solve using this library. Remember that the original form of your code library should be easier to use and remember in solving problems. The simpler the API, the easier it is for users to learn your code library. Introduce a Unix Design Philosophy:

Only do one thing and do it well

Ask yourself: What problems does your code library solve? How are you going to solve it? Will you do all your work by yourself or introduce someone else's code library?

Regardless of the size of the code library, try to create a roadmap. List all the features you want and scatter them as much as possible, knowing that you have a small but problematic code base, just like minimum viable product. This will become your first version. From here on, you can build milestones for every new feature. Essentially, you turn your project into a bit-level code block, making every feature better and more interesting. Believe me, this will keep you in good state.

API design

In my opinion, I want to develop my code library from the user's perspective. You can call it a user-centered design. In essence, you are creating an outline of your code library, giving it more thinking and making it easier for people who choose it to use it. At the same time, you need to think about where customization is needed, which will be discussed later in this article.

The ultimate API test is to try your own technology and use your code library in your project. Try to replace the previous code with your code library to see if it meets the features you want. Try to make your code library as intuitive as possible, so that it can be used more flexibly under boundary conditions, as well as customization (as described in later articles ).

This is an outline of the code library for the user proxy string, which may look like:

// Start with empty UserAgent string var userAgent = new UserAgent; // Create and add first product: EvilCorpBrowser/1.2 (X11; Linux; en-us) var application = new UserAgent.Product('EvilCorpBrowser', '1.2');application.setComment('X11', 'Linux', 'en-us');userAgent.addProduct(application); // Create and add second product: Blink/20420101 var engine = new UserAgent.Product('Blink', '20420101');userAgent.addProduct(engine); // EvilCorpBrowser/1.2 (X11; Linux; en-us) Blink/20420101 userAgent.toString(); // Make some more changes to engine product engine.setComment('Hello World'); // EvilCorpBrowser/1.2 (X11; Linux; en-us) Blink/20420101 (Hello World) userAgent.toString();

Depending on the complexity of your code, you may spend some time on the organizational structure. Using design patterns is a good way to organize your code library, and you can even solve some technical problems. This also avoids the wide-area reconstruction caused by new features.

Flexibility and customization

Flexibility is a factor that makes the code library powerful, but it is difficult to determine the boundaries between customization and non-customization. Chart. js and D3.js are good examples. Both code libraries are used for data visualization. Chart. js can easily create built-in charts of different forms. But if you want to have more control over the image, D3.js is what you need.

There are several ways to give control to the user: configuration, exposure of public methods, through callback and events.

The configuration code library is usually completed before initialization. However, some code libraries allow you to modify the configuration during runtime. Configuration is usually limited by a small part. It is only allowed to modify their values for later use.

// Configure at initialization var userAgent = new UserAgent({  commentSeparator: ';' }); // Run-time configuration using a public method userAgent.setOption('commentSeparator', '-');   // Run-time configuration using a public property userAgent.commentSeparator = '-';

Methods are usually exposed to instances, for example, getting data from instances, or setting instance data and performing operations.

var userAgent = new UserAgent; // A getter to retrieve comments from all products userAgent.getComments(); // An action to shuffle the order of all products userAgent.shuffleProducts();

Callback is usually passed in public methods, and user code is usually executed after asynchronous operations.

var userAgent = new UserAgent;userAgent.doAsyncThing(function asyncThingDone() { // Run code after async thing is done });

There are many possibilities for events. It is a bit like callback. operations should not be triggered unless the event handle is added. Events are usually used for listening. You may guess this is an event! More like callback, You can provide more information and return a value to the code library for operations.

var userAgent = new UserAgent; // Validate a product on addition userAgent.on('product.add', function onProductAdd(e, product) { var shouldAddProduct = product.toString().length < 5; // Tell the library to add the product or not return shouldAddProduct;});

In some examples, you may allow users to expand your code library. Therefore, you need to expose some public methods or attributes to fill users, such as Angular modules (angular. module ('mymodule') and Jquery fn (jQuery. fn. myPlugin) or do nothing, but simply let the user get the namespace of your code base:

// AngryUserAgent module // Has access to UserAgent namespace (function AngryUserAgent(UserAgent) { // Create new method .toAngryString() UserAgent.prototype.toAngryString = function() { return this.toString().toUpperCase();  };})(UserAgent); // Application code var userAgent = new UserAgent; // ... // EVILCORPBROWSER/1.2 (X11; LINUX; EN-US) BLINK/20420101 userAgent.toAngryString();

Similarly, this allows you to override the method.

// AngryUserAgent module (function AngryUserAgent(UserAgent) { // Store old .toString() method for later use var _toString = UserAgent.prototype.toString; // Overwrite .toString() UserAgent.prototype.toString = function() { return _toString.call(this).toUpperCase();  };})(UserAgent); var userAgent = new UserAgent; // ... // EVILCORPBROWSER/1.2 (X11; LINUX; EN-US) BLINK/20420101 userAgent.toString();

In the following example, you can allow your users to obtain the namespace of the code library, which makes your control over the extensions and plug-ins become smaller. To keep the plug-in compliant with some conventions, you can (or should) write down the document.

Test

Writing an outline is a good start for test-driven development. To put it simply, before you write the actual code library, you write the test criteria. If the test checks whether your code features are the same as expected, and you write the test before writing the code base, this is behavior-driven development. In any case, if your test covers every feature of your code library and your code passes all the tests. You can make sure that your code works properly.

Jani Hartikainen describes how to use Mocha to perform Unit Test Your JavaScript Using Mocha and Chai. In this article, we use Jsmine, Travis, Karma to test JavaScript (Testing JavaScript with Jasmine, Travis, and Karma, tim Evko shows how to set up a good test process through another framework called Jasmine. These two testing frameworks are both very popular, but there are other frameworks that adapt to other needs.

The outline I wrote earlier in this article already describes what output it expects. This is the beginning of all tests: Starting from expectation. A Jasmine test on my code library is like this:

describe('Basic usage', function () {  it('should generate a single product', function () { // Create a single product var product = new UserAgent.Product('EvilCorpBrowser', '1.2');    product.setComment('X11', 'Linux', 'en-us');    expect(product.toString())      .toBe('EvilCorpBrowser/1.2 (X11; Linux; en-us)');  });  it('should combine several products', function () { var userAgent = new UserAgent;   // Create and add first product var application = new UserAgent.Product('EvilCorpBrowser', '1.2');    application.setComment('X11', 'Linux', 'en-us');    userAgent.addProduct(application); // Create and add second product var engine = new UserAgent.Product('Blink', '20420101');    userAgent.addProduct(engine);    expect(userAgent.toString())      .toBe('EvilCorpBrowser/1.2 (X11; Linux; en-us) Blink/20420101');  });  it('should update products correctly', function () { var userAgent = new UserAgent;   // Create and add first product var application = new UserAgent.Product('EvilCorpBrowser', '1.2');    application.setComment('X11', 'Linux', 'en-us');    userAgent.addProduct(application); // Update first product application.setComment('X11', 'Linux', 'nl-nl');    expect(userAgent.toString())      .toBe('EvilCorpBrowser/1.2 (X11; Linux; nl-nl)');  });});

Once you are fully satisfied with the first version of your API design, it is time to start thinking about the structure and how your code library should be used.

Module loader compatibility

You may have used the module loader. Developers using your code library may use loaders, so you may want your code library to be compatible with the module loaders. But which one is compatible? How can I choose from CommonJS, RequireJS, AMD, and other loaders?

In fact, you don't need to select it! The general-purpose module definition (UMD) is a rule that supports multiple loaders. You can find code segments of different styles on the Internet, or learn from UMD GitHub repository and make it compatible with your code library. You don't have to worry about the module Loader from a template or use your favorite build tool to add UMD with your favorite build tool.

If you want to use ES2015's import/export syntax, I suggest using Babel and Babel's UMD plugin to convert the code to es5. With this method, you can use ES2015 in your project and generate a code library with good compatibility.

Document

I fully agree to the use of documents in every project. However, this usually involves a lot of work, resulting in the preparation of documents being delayed and finally forgotten.

Basic Information

The preparation of the document should begin with basic information such as the Project Name and description. This will help others understand what your code library has done and whether it is useful to them.

You can provide information such as the scope and target to better provide information to users, providing a roadmap allows them to understand what new changes may occur in the future and how they can help.

APIS, tutorials, and examples

Of course, you need to ensure that users know how to use your code library. This starts with the API documentation. Tutorials and examples are a good supplement, but writing them will be a huge task. However, Inline documentation does not. Below are some notes that can be parsed and converted into document pages using JSDoc.

Meta-task

Some users want to improve your code library. In most cases, code is contributed, but some will create a customized version for private use. These users provide documentation for Meta tasks such as building code libraries, running tests, generating, transforming, and downloading data.

Contribution

When you open source your code library, it is very helpful to get the code contribution. To guide contributors, you can add some documents about the contribution code steps and standards to be met. This will help you review and accept contributed code and correct contributed code.

Authorization

Finally, use the authorization permission. Technically, without selecting any technology license, your code library is still copyrighted, but not everyone knows this.

I found that the ChooseALicense.com website allows you to select an authorization license without becoming a legal expert. After selecting the authorization license, you only need to add the LICENSE.txt file under the root directory of the project.

Package and publish it to the Package Manager

For a good code library, version is very important. If you want to add significant changes, users may need to retain the version they are currently using.

Semantic Versioning is a popular version Naming Standard, or SemVer. The SemVer version contains three numbers, each representing a change of varying degrees: major changes, minor changes, and patches.

Add version and release in your Git Repository

If you have a git repository, you can add version numbers in your repository. You can think of it as a snapshot of Your repository. We also call it Tags. You can create tags by enabling the terminal and entering the following text:

# git tag -a [version] -m [version message]git tag -a v1.2.0 -m "Awesome Library v1.2.0"

Many services similar to GitHub provide an overview of all versions and download links for them.

Publish a general Repository

Npm

Many programming languages come with a package manager or a third-party package manager. This allows us to download specific code libraries for these languages. For example, PHP Composer and Ruby RubyGems

Node. js is an independent JavaScript Engine with npm. If you are not familiar with npm, we have a good tutorial beginner's guide.

By default, your npm package will be published as a public package. Do not be afraid. You can also publish private packages, set a private registry to be registered, or do not publish avoid publishing.

To publish your package, your project requires a package. json file. You can create an interactive Q & A manually. Enter the following code to start the Q &:

`npm init`

This version attribute must match your git tag. Make sure the README. md file is available. Like GitHub, npm uses it on the display page of your package.

Then, you can enter the following code to release your package:

`npm publish`

That's it! You have released your npm package.

Bower

A few years ago, there was another package manager called Bower. This package manager is actually not prepared for a specific language, but for the Internet. You can find that most of the resources are front-end resources. The key to releasing your package in Bower is whether your code library is compatible with it.

If you are not familiar with Bower, we also have a beginner's guide.

Like npm, you can also set a private repository. You can avoid publishing through Q &.

Interestingly, in the past one or two years, many people have switched to npm to manage frontend resources. The recent npm package is mainly related to JavaScript, and most of the front-end resources are also released on npm. In any case, Bower is still popular. I recommend you release your package on Bower.

I have mentioned that Bower is actually a module of npm and was initially inspired by it? Their commands are similar. The following code is used to generate the bower. json file:

`bower init`

Like npm init, the command is straightforward. Finally, release your package:

`bower register awesomelib #`

Like putting your code library in the wild, anyone can use it on their Node project or network!

Summary

The core product is library files. Make sure it solves the problem and is easy to use. You will make your team or many developers happy.

Many of the tasks I mentioned are automated, such as running tests, creating tags, upgrading packages in package. json, or re-releasing your packages in npm or bower. This is the beginning of continuous integration and use of tools like Travis CI or Jenkins. The article I mentioned earlier, article by Tim Evko, also tells this.

Have you built and released the code library? Please share it in the comment area below!

The above describes how to design and build your own JavaScript code library: Tips and tips. For more information, see the PHP Chinese website (www.php1.cn )!

Related Article

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.