问题
I'm using require.js with r.js to optimize. Pre-optimization, I have:
// MainCtrl.js
define(function () {
return ["$scope", function ($scope) { console.log($scope); }];
});
// main.js
require.config({
shim: {
angular: {
exports: "angular",
},
},
paths: {
angular: "lib/angular.min",
},
});
require(["angular", "MainCtrl"], function (ng, MainCtrl) {
console.log(ng);
var app = ng.module("myapp", []);
app.controller("MainCtrl", MainCtrl);
});
My HTML is very simple; it just has ng-app=myapp in <html> and ng-controller=MainCtrl on <body>.
When I run the app like this, everything seems to work. I get the console.log for ng which appears to be the angular object. Then, I get the console.log for $scope from MainCtrl. No problems.
After running r.js and using the minified main.js, I get errors and things no longer work. I run r.js -o build.js.
// build.js
({
appDir: "public",
baseUrl: "js",
dir: "dist",
fileExlusionRegExp: /^(r|build\.js)$/,
optimize: "uglify2",
optimizeCss: "standard",
modules: [{
name: "main"
}],
paths: {
angular: "lib/angular.min",
},
})
Now when I visit index.html I get errors:
Uncaught Error: [$injector:modulerr] undefined Uncaught TypeError: Cannot call method 'module' of undefined
- Seems to indicate that angular is not loading properly or something. It can't inject something to
myapp, but it has no dependencies. NotngRouteor anything ngis now undefined even though it was correctlyangularbefore. This also causes the second error- The
console.loginMainCtrlis not called. Not a huge surprise since there is an error on the previous line. However, if I changengtoangulartheundefinederror does not occur andapp.controllergets called, but theconsole.logfromMainCtrlis still not called.
My only guess is that angular is being minified twice (I'm already using angular.min.js and then r.js minifies it again). Can I do anything to fix this issue?
回答1:
In the shim documentation, it is suggests:
You should use the mainConfigFile build option to specify the file where to find the shim config. Otherwise the optimizer will not know of the shim config. The other option is to duplicate the shim config in the build profile.
This is probably causing angular's shim to be absent from the built file.
来源:https://stackoverflow.com/questions/19866868/injectormodulerr-after-r-js-optimization-but-not-before