Make your own JS module compatible with AMD CMD CommonJS

Source: Internet
Author: User

In order to allow the same module to run on the front and back end, it is necessary to consider the compatibility front end and the module specification environment in the writing process. In order to maintain the consistency of the front and back end, class library developers need to wrap the class library code inside a closure. The following code shows how the Hello () method can be defined in a different run environment, compatible with node (CommonJS), amd,cmd, and common browser environments:

(function(name, definition) {//detects if the context is AMD or CMD    varHasdefine =typeofdefine = = = ' function '; //Check if the context is a node    varHasexports =typeofModule!== ' undefined ' &&Module.exports; if(hasdefine) {//AMD Environment or CMD environmentdefine (definition); } Else if(hasexports) {//defined as normal node moduleModule.exports =definition (); } Else {        //hangs the execution result of the module in the window variable, which in the browser points to the Window object         This[Name] =definition (); }})(' Hello ',function () {    varHello =function () {}; returnhello;});

The principle of compatibility and our usual browser-compatible principle is the same, nothing more than the ability to detect and quirks detection.

Make your own JS module compatible with AMD CMD CommonJS

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.