js模組化之自定義模組(頁面模組化載入)

月夜原野發表於2017-10-16
轉自:http://blog.novanet.no/4-strategies-for-passing-parameters-to-requirejs-modules/
轉自:http://javascript.ruanyifeng.com/tool/requirejs.html
入口:main1.js

require.config({
baseUrl : 'js',
paths : {
'main':'main'
}
});
require([  'main' ], function(main) {
var a = main.add1(1,54);
alert(a);

});
main1.js引用的main.js
require.config({
baseUrl : 'js',
paths : {
'jquery' : 'jquery/jquery-1.10.2',
'd3' : 'd3/d3',
'echarts' : 'echart/echarts.min'
}
});

define([ 'jquery', 'd3', "echarts" ], function(jquery,d3,echart) {
return {
add1 : function(x, y) {
return x + y;
}
};
});
說明:
在requirejs的模組路徑解析裡,baseUrl是非常基礎的概念,離開了它,基本就玩不轉了,所以這裡簡單介紹一下。
簡單的說,baseUrl指定了一個目錄,然後requirejs基於這個目錄來尋找依賴的模組。
如果指定了baseUrl,則按照baseUrl目錄為基準目錄載入其他依賴的js;
如果沒有指定baseUrl,則預設按照data-main檔案所在的目錄為基準目錄載入其他依賴的js;
如果沒有通過data-main屬性指定baseUrl,也沒有通過config的方式顯示宣告baseUrl,那麼baseUrl預設為載入requirejs的那個頁面所在的路徑

jsp頁面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>testD3-20-pie.html</title>
<script data-main="${pageContext.request.contextPath}/test/js/main1.js" src="${pageContext.request.contextPath}/test/js/required/require.js"></script>
<script type="text/javascript">
    require(['${pageContext.request.contextPath}/test/js/main1.js'], function(app){
        var rootPath = "${pageContext.request.contextPath}";
                var config = {
                    "rootPath" : rootPath                     
                };
                app.xxxx(config);
            });  
</script>
<style type="text/css">

</style>
</head>
<body>
 <div style="width:300px;height:300px;" id="div1">
 
 </div>

</body>
</html>

 注:data-main="${pageContext.request.contextPath}/test/js/main1.js" 的作用是指定js的入口,確定載入的基準目錄;
 require(['${pageContext.request.contextPath}/test/js/main1.js'], function(app){});
的作用是載入模組的過程,將main1.js依賴的包全部載入,然後返回main1.js中defined的函式物件;
之後在回撥函式function(app)中寫呼叫方法;



將模組載入到頁面中有四種方法:

#1 Passing parameter to method

Starting of slow, we let our require module return a JavaScript object with a method that accepts a parameter. This is pretty basic stuff, and should be sufficient for most scenarios.

index.html
<script src="scripts/require.js"></script>
<script>
    require(['scripts/app'], function(app){
        app.greet('World');
    });
</script>
app.js
define(function(){
    return {
        greet: function(name){
            alert('Hello ' + name);
        }
    };
});

#2 Passing object to method

While #1 works great when you have one, or only a handful of parameters, it can get quite messy when you're dealing with a lot of parameters. To counter this we can let our module accept an object instead.

index.html
<script src="scripts/require.js"></script>
<script>
    require(['scripts/app'], function(app){
        app.greet({
            salutation: 'Dr.',
            name: 'Who'
        });
    });
</script>
app.js
define(function(){
    return {
        greet: function(config){
            alert('Hello ' + config.salutation + ' ' + config.name);
        }
    };
});

#3 Using RequireJS configuration

By loading the pre-defined RequireJS module aptly named "module" into your own module, you can define and access configuration data.

Note: The definition must be done before you include the require.js file, and this only works for define and not require modules.

index.html
<script>
    var require = {
        config: {
            'app': { //This must match your module name
                name: 'Sherlock'
            }
        }
    };
</script>
<script data-main="scripts/app" src="scripts/require.js"></script>
app.js
define(['module'], function(module){
    alert('Hello ' + module.config().name);
});

#4 Using a separate configuration module

Sometimes you'll have multiple modules needing the same input, then you can define a separate configuration module, and load it into your module like any other. I think this gives an nice clean separation between logic and data, but it can be a bit of an overkill i many situations.

index.html
<script>
    var require = {
        config: {
            'config': {
                name: 'Everybody'
            }
        }
    };
</script>
<script data-main="scripts/app" src="scripts/require.js"></script>
config.js
define(['module'], function(module){
    return {
        name: module.config().name
    }
});
app.js
require(['config'], function(config){
    alert('Hello ' + config.name);
});

相關文章