前端代码模块化之requireJS_Alice

第一步:下载require.js,创建HTML文件添加引用,确保自己的路径设置正确。

 <script src="../ThirdParty/requirejs-2.1.20/require.js"></script>
 

第二步:创建功能模块.js文件,最好一个.js文件定义一个模块。


(function () {

    define('Singulation',[], function(){
        'use strict';
        var Singulation = {
            VERSION : '1.0'
        };

        function buildingHighlightFun() {
        console.log('so easy!');
        }
        
        Singulation["buildingHighlightFun"] = buildingHighlightFun;
        return Singulation;
    });

    /*global require*/
    // require in the complete Cesium object and reassign it globally.
    // This is meant for use with the Almond loader.
    require([
        'Singulation'
    ], function(
        Singulation) {
    'use strict';
    /*global self*/
    var scope = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {};

    scope.Singulation = Singulation;
    }, undefined, true);
}());

第三步:在上面的HTML中继续添加上面创建的js文件

 <script src="../ThirdParty/requirejs-2.1.20/require.js"></script>
 <script src="jsFile/Singulation.js"></script>

然后就可以在脚本中任性地使用这个模块了:

Singulation.buildingHighlightFun();

注意:如果遇到提示全局变量Singulation未定义的错误,那就给模块使用做一个延时执行,因为异步加载,可能会造成在模块未加载时,已经执行了调用操作。

本文转自 https://blog.csdn.net/qq_18144905/article/details/82697758,如有侵权,请联系删除。

原文地址:https://www.cnblogs.com/hustshu/p/15248728.html