使用mini-define实现前端代码的模块化管理

这篇文章主要介绍了使用mini-define实现前端代码的模块化管理,十分不错的一篇文章,这里推荐给有需要的小伙伴。

mini-define

依据require实现的简易的前端模块化框架。如果你不想花时间学习require.js,也不想翻看长篇的cmd/amd规范,那么这个mini-define就是你不错的选择。如果你之前用过sea.js或require.js那么mini-define更加高效,更加轻量,更加易用。项目地址:github

用法

首先定义模块

定义模块

一:定义模块用define函数

1.1 根据是否有依赖,有两种情况:

1.1.1:没有依赖的模块

    define('id',function(){
            // put your code here
        });

1.1.2:有依赖的模块

  define('id',['modeA','modeB'],function(A,B){
            // put your code here
        });

1.2 根据是否需要返回处理结果给外部使用,又可以分两种情况:

1.2.1有返回对象:

 define('id',function(){
                return {
                    // put your code here
                }
            });

1.2.2 没有返回对象

   define('id',function(){
                // put your code here
            });

二: 调用模块用require()函数

2.1 根据请求的模块数,可以有两情况:

    2.1.1.调用单个模块

        require('modeId')

    2.1.2.调用多个模块
            require(['modeA','modeB']);
2.2 根据是否有回调处理,又可以分为两种情况:

    2.2.1 有回调处理函数

  require('modeId',function(mode){
                //put your code here
            });
            require(['modeA','modeB'],function(A,B){
                //put your code here
            });

.2.2 没有回调处理
            require('modeId');
然后在index.html页面依次引用所需模块

!--核心模块-->
<script src="lib/core/require.js"></script>
<!--用于演示的模块-->
<script src="lib/main.js"></script>
<script src="lib/config.js"></script>
<script src="lib/init.js"></script>

最后就是用你喜欢的方式对lib目录进行合并压缩,生成一个min.js文件。 在发布应用的时候,相应的index.html也需要调整一下:

<script src="lib/min.js"></script>
原文地址:https://www.cnblogs.com/jymz/p/4221693.html