JS modular development - making js more standardized

Why is there modularity

  • Naming conflicts : When a project is collaboratively developed by a team, the variables and functions of different developers may have the same names; even for one development, when the development cycle is relatively long, it is possible to forget what variables were used before, resulting in duplication naming, leading to naming conflicts.

  • File dependency : When code is reused, the number of imported js files may be less, or the order of importing is wrong. For example, when using boostrap, jQuery needs to be imported, and jQuery files must be imported before boostrap's js files.

  • Excessive code coupling: Efficiency and speed are the focus nowadays, especially in the development of hybrid APPs. If the code repetition rate is too high, the local resource package will be too large, which will reduce the size of the resource package infinitely. It will affect the execution efficiency of the code, etc.

What are the benefits of modular development?

  • Improve development efficiency : the code is easy to reuse, modules developed by others can be used directly, and there is no need to repeatedly develop similar functions.

  • Convenient post-maintenance : the code is easy to reuse, the modules developed by others can be used directly, and there is no need to repeat the development of similar functions.

So how to do modular development?

There are so many ways

1. require method (AMD mode)

test.js

// 首先使用define进行定义
define(function(){
    function fun1(){
      alert("it works");
    }
    fun1();
})

// 在页面中使用require进行引用
require(["js/a"]);

The problem with requireJs is that when added to a module, all dependent modules of the module will be preloaded, but these dependencies are likely not to be used at the beginning. At the same time, it is very troublesome to write a long list of dependencies. The better thing is that AMD retains the require, exports, and module functions in commonJs, so you don't need to write them all in dependencies, but use require to import them when needed.

2. The rising star SeaJs (CMD mode)

  1. Import sea.js library
  2. define module
  3. define(function(require, exports, module){module code});
  4. require('module id')
  5. seajs.use('module id', function(module object){business code});

3. ES2015 module standard

ES6 considers modularity, using import and export, the code is more concise, and there are many new features to make development more convenient.

Guess you like

Origin blog.csdn.net/qq_23334071/article/details/82765446