js模組載入seajs架構的教程

來源:互聯網
上載者:User

有些時候,我們不得不寫一些前段的東西,但是總感覺前段載入的太亂,管理起來不方便,載入也是問題,其實以前不會寫頁面,但是偶然機會開始一直寫頁面+寫程式了。我的使用搭配方案是 seajs + angularjs + bootstrap + jquery + grunt + less 。

為什麼使用的是 Grunt 其實很簡單,因為我也需要編譯 less 檔案,實施監控檔案的改動和對 html 、 js 、css 進行壓縮。當然不僅僅是這些,功能很強大,我就不一一介紹了。只是個人喜好而已。感覺這東西跟 golang 中的 bee Application 差不多。你也可以選擇你所喜歡的。

一般的 CSS 我使用的是 less 因為 bootstrap 中也是提供了完整的 less 檔案,開發和定製前端,最重要的是維護起來真的很方便,不得不這麼說。
0X01 seajs 載入原生的 JQuery

很簡單,只需要如下就可以

 代碼如下 複製代碼

define(function(){
    //這裡放JQuery原始碼
    return $.noConflict();
});

其實就是將,下載的 JQuery 的原始碼放到注釋的部分載入就可以了。

0X02 angular js 模組如何載入

angular js 如何載入生效呢? 不能用了咋辦? 其實也一樣很簡單,如下

 代碼如下 複製代碼

define(function(require,exports,module){
    // angular js 原始碼
    module.exports = angular;
});

只需要在注釋的地方假如 angular js 原始碼就可以了。

如果使用 angular js的其他模組,譬如route ,只需要將原始碼包在 define(function(){ }) 中就可以,如下

 代碼如下 複製代碼

define(function(){
    //angular-route 原始碼
})

然後,你就可以寫一段代碼測試一下了,如下

 代碼如下 複製代碼

define(function(require,exports,module){
    var angular = require('angular');
    require('angular-route');
    var app  = angular.module('myapp',['ngRoute']).config(function($routeProvider){
            $routeProvider.when('/',{
                controller : function($scope){
                    $scope.message = '這裡是首頁';
                },
                template  : "{{message}}"
            }).when('/list/:id',{
                controller : function($scope,$routeParams){
                    $scope.message = $routeParams.id;
                },
                template  : "您的使用者id是{{message}}"
            }).when('/product',{
                controller : function($scope){
                    $scope.message = "這裡是產品頁";
                },
                template  : "{{message}}"
            }).otherwise({
                redirectTo : '/'
            });
        });
    app.controller('test',['$scope','$location',function($scope,$location){
        $scope.message = 'widuu.com';
    }]);
});

0X03 grunt 壓縮時 angularjs 失效問題

這個也很簡單,其實就是將特定的命名再壓縮的時候不編譯。在你的 uglify -> 項目 -> mangle 添加except

 代碼如下 複製代碼
mangle: {
    except: ['require', 'exports','module','$','jquery','angular','$routeProvider','$scope','$routeParams']
},

就簡單說到這吧!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.