Uncaught Error: No module: MyApp

2019-04-15 23:57发布

问题:

I load AngularJs and jQuery using RequireJs in nodeJs framework.

That is main.js

    require.config({
    paths: {
        angular: 'vendor/angular.min',
        bootstrap: 'vendor/twitter/bootstrap',
        jquery: 'vendor/jquery-1.9.0.min',
        domReady: 'vendor/require/domReady',
        underscore: 'vendor/underscore.min'
    },
    shim: {
        angular: {
            deps: [ 'jquery' ],
            exports: 'angular'
        }
    }
});

require([
        'app',
        'angular-boot'
    ], function() {

});

in app.js

 define(['angular'], function (angular) {
    return angular.module('MyApp', []);
})

and in angular-boot.js

    define([ 'angular', 'domReady' ], function (angular, domReady) {
    domReady(function() {
        angular.bootstrap(document, ['MyApp']);
    });
});

In my html file I have only this line, in order to declare and use requirejs. Not ng-ap or anything else.

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

The problem is that sometimes runs, sometimes not. The error when it doesn't run is

Uncaught Error: No module: MyApp

If there is any thought about it, I would really appreciate it. Thank you very much.

回答1:

In your shim, you need to setup the app as a dependency to angular-boot. Your angular-boot file depends on app (where MyApp is defined), and because the load order for these two files is not specified, sometimes angular-boot loads before the app and thus produces that error.

To remedy, just update your shim as such:

shim: {
  angular: {
    deps: [ 'jquery' ],
    exports: 'angular'
  },
  'angular-boot': {
    deps: ['app']
  }
}

and than, since you don't need to include the 'app' explicitly your require call can be reduced to:

require(['angular-boot']);