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