2

I am writing jquery plugin. Because the plugin contains a lot of code I decided to separate the code into several files and use require.js. I am trying to achieve two things:

  1. The ability to run my test page using require.js with the separated version of the plugin, and by this be able to debug the code.
  2. The ability to use require.js optimizer (called r.js) and create one optimized (combined and minified) file from those several plugin's files.

My index.html contains:

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

My js/site.js contains:

require([
    'jquery',
    ....
    ....
    'main' //<---- main plugin file
], function($) {

    $(function() {
        $('#elem').photosGrid();
    });
});

And my main.js file contains:

define([
    'photos-grid' //<---- Class that initialized and build the plugin
], function(PhotosGrid) {
    jQuery.fn.photosGrid = function(options) {
        var photosGrid = new PhotosGrid(this, options);
        this.data('photosGrid', photosGrid);
        return this;
    };

    return jQuery;
});

In order to configure r.js, I added build.js file:

({
    baseUrl: '.',
    name: "main",
    out: "main-built.js"
})

When I run my index.html my plugin works great. But when I run node r.js I get the following error:

Error: Mismatched anonymous define() module

When I define main.js with a name:

define('module-name', ['photos-grid'], function(PhotosGrid) { .....

node r.js returns no error but no output come out. Moreover, index.html don't load the dependencies of main.js ('photos-grid') and as a result the website doesn't work.

What am I doing wrong? How can I use r.js properly?

4

1 回答 1

3

You forgot to pass the -o flag to run r.js in the optimizer mode! More details in the official docs

(...this seems to be one of the most popular problems with r.js)

于 2013-03-30T19:17:22.107 回答