Hanpan
Hanpan

Reputation: 10261

RequireJS - Performance difference with define vs require

I'm trying to understand if there are any potential downsides to the way I am using requirejs. I am fan of using the commonjs syntax, a typical module will look like:

define(function(require) {
    "use strict";

    var Backbone = require('backbone');
    var Templates = require('templates');
    var User = require('accounts/models').User;
...

I then compile my application down to a single JS file. My build config looks like so:

name: 'main',
mainConfigFile: '<%= build_dir %>/<%= main_app %>',
out: '<%= build_dir %>/app.min.js',
optimize: 'none',
include: ['main'],
insertRequire: ['main'],
almond:true,
cjsTranslate: true,
findNestedDependencies: true,
preserveLicenseComments: false

My question is, does using this commonjs format pose any performance or optimisation issues that I would avoid if using a define array instead? As I understand it, the cjsTranslate argument converts it to a define call anyway, but I wasn't sure if there was something I was missing? Is it purely a preference / code readability thing?

For reference, my config file (main.js):

require.config({
    paths: {
        // Libraries
        jquery: '../../vendor/jquery/jquery',
        underscore: '../../vendor/underscore/underscore',
        backbone: '../../vendor/backbone/backbone',
        handlebars: '../../vendor/handlebars.js/dist/handlebars',
        modernizr: '../../vendor/modernizr/modernizr',

        templates: '../templates'
    },

    shim: {
        "underscore":{
            exports: "_"
        },
        "backbone": {
            deps: ["underscore", "jquery", "modernizr", "moment"],
            exports: "Backbone"
        },
        "handlebars": {
            exports: "Handlebars"
        }
    }
});

Upvotes: 2

Views: 273

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44649

Is it purely a preference / code readability thing?

Yes absolutely. Once you build, R.js convert Commonjs to plain AMD.

The only performance hit would be when using unbuilded project. But for development it is fast enough (I see no clear difference myself).

Upvotes: 2

Related Questions