使用require.js定义多层依赖项

时间:2013-06-01 03:57:34

标签: angularjs requirejs

我正在使用AngularJS,Bootstrap和Jquery创建一个小型Web框架。我将在此框架中添加几个可重用的角度指令。该框架将被其他几个Web应用程序使用。这是结构

WebApp1
 |-js
 |  |_testFramework.js
 |  |_lib
 |  |  |_angular.min.js
 |  |  |_bootstrap.min.js
 |  |  |_jquery.min.js
 |  |_main.js
 |  |_require.js
 |  |_controllers.js
 |_index.html

我的testFramework.js看起来像这样

require.config({
    paths: {
        jquery: 'lib/jquery.min',
        angular:'lib/angular.min',
        bootstrap:'lib/bootstrap.min',
    },
    shim: { 
      'angular' : {exports:'angular'},
    }
});

define(['angular'],function(angular){   
    console.log('framework loaded');
    var fw = angular.module("framework",[]);
    ff.directive("dir1",function(){

        }.directive("dir2",function(){

        }
}

我的Main.js如下

require.config({
    paths: {
        fw: 'framework',
        controllers: 'controllers'
    }
});

define(['fw','angular'],
    function(fw, angular){
    var app = angular.module("myWebApp1",['fw']);
            $routeProvider.when('/login',{templateUrl:'partials/login.html'});  
        $routeProvider.otherwise({redirectTo: '/login'});
    }])        

    console.log('app loaded');
    }
);

Index.html已

<script data-main="js/main.js" src="js/require.js"></script>

但是当我尝试加载应用时,我总是得到以下错误

"NetworkError: 404 Not Found - https://localhost:8000/WebApp1/js/angular.js"

为什么要尝试从/ js加载角度,而不是testFramework.js中提到的

1 个答案:

答案 0 :(得分:3)

尝试splitting the config out from the application JS

步骤

  • 创建requirejs config
  • import requirejs
  • 使用模块

HTML

<script>
var require = {
  paths: {
    'jquery': '//code.jquery.com/jquery-1.9.1',
    'angular': '//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min',
    'bootstrap': '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min',
    'my-library': '//gist.github.com/gitgrimbo/5689953/raw/9b44d7e5f504b2245331be3ed3fcbb7bf8635da6/gistfile1'
  },
  shim: {
    'bootstrap' : {deps:['jquery']},
    'angular' : {exports:'angular'}
  }
};
</script>
<script
    data-main="https://gist.github.com/gitgrimbo/5690017/raw/aea9f61c47e9250b89c3d8fdb7511582f81664a4/gistfile1.js"
    src="http://requirejs.org/docs/release/2.1.5/comments/require.js">
</script>

gistfile1.js(又名main.js)

define(["angular", "my-library", "bootstrap"], function (angular, myLibrary, bootstrap) {
    console.log(angular.version);
    console.log(myLibrary);
    console.log(undefined === bootstrap, "bootstrap augments jQuery and has no module return value");
    console.log("1.9.1" === $.fn.jquery, "boostrap should have caused jQuery to load");
    console.log("function" === typeof $.fn.alert.Constructor, "boostrap adds alert");
});

控制台输出

Object { full="1.0.6", major=1, minor=0, more...}
my-library
true bootstrap augments jQuery and has no module return value
true boostrap should have caused jQuery to load
true boostrap adds alert