简体   繁体   中英

requirejs: requiring an r.js optimized file

I've built a web app using require.js, and successfully used r.js to combine all module definitions into a single file.

Once the r.js optimized file has been created, I expected to just be able to require the optimized file on its own, but it fails to execute any of code after loading and defining the modules:

require([
    'app1/optimizedAppFile'
], function (optimizedApp) {

    //optimizedApp is undefined, even though it loaded 
    //the file and executed the module definitions in debugger

});

Is it appropriate to load / instantiate the app by defining the path to the top level module of the optimized file in require.config.js, and then requiring that in main.js? ie

requirejs.config({

    paths: {
        'optimizedApp.topLevelModule' : 'app1/optimizedAppFile'
        //optimizedApp.topLevelModule is the full module name
        //app1/optimizedAppFile is the combined file from r.js
    }

});

Yes, after optimized your code via rjs, you can just require that file.

However, I had this problem today as well. After spending hours debugging I found out the current 1.1.2 backbone version has a piece of code detecting if AMD (the function "define" exists).

after removing it, backbone looks like this

//     Backbone.js 1.1.2

//     (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org

(function(root, factory) {
  root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender ||     root.$));
}(this, function(root, Backbone, _, $) {

So basically what I did is make it globally accessible and add shim for it

 require.config({
  baseUrl: "/static/src/scripts/js",
  paths: {
    jquery: 'vendors/jquery/jquery',
    underscore: 'vendors/underscore/underscore',
    backbone: 'vendors/backbone/backbone',
    marionette: 'vendors/backbone/backbone.marionette'
  },
  shim: {
    jquery: {
      exports: "jQuery"
    },
    underscore: {
      exports: "_"
    },
    backbone: {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone'
    },
    marionette: {
      deps: ['backbone'],
      exports: 'Marionette'
    }
  }
});

Inspect element and check your console and see what it complains, and turns of optimize by setting the optimize option to false for the rjs and look for which part it errors out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM