Coder Social home page Coder Social logo

almond's Introduction

almond

A replacement AMD loader for RequireJS. It provides a minimal AMD API footprint that includes loader plugin support. Only useful for built/bundled AMD modules, does not do dynamic loading.

Why

Some developers like to use the AMD API to code modular JavaScript, but after doing an optimized build, they do not want to include a full AMD loader like RequireJS, since they do not need all that functionality. Some use cases, like mobile, are very sensitive to file sizes.

By including almond in the built file, there is no need for RequireJS. almond is around 1 kilobyte when minified with Closure Compiler and gzipped.

Since it can support certain types of loader plugin-optimized resources, it is a great fit for a library that wants to use text templates or CoffeeScript as part of their project, but get a tiny download in one file after using the RequireJS Optimizer.

If you are building a library, the wrap=true support in the RequireJS optimizer will wrap the optimized file in a closure, so the define/require AMD API does not escape the file. Users of your optimized file will only see the global API you decide to export, not the AMD API. See the usage section below for more details.

So, you get great code cleanliness with AMD and the use of powerful loader plugins in a tiny wrapper that makes it easy for others to use your code even if they do not use AMD.

If you want a single file build output but without the module APIs included, you might want to consider AMDclean.

Restrictions

It is best used for libraries or apps that use AMD and:

  • optimize all the modules into one file -- no dynamic code loading.
  • all modules have IDs and dependency arrays in their define() calls -- the RequireJS optimizer will take care of this for you.
  • only have one requirejs.config() or require.config() call.
  • the requirejs.config/require.config call needs to be included in the build output. This is particularly important for making sure any map config use still works.
  • do not use the var require = {}; style of passing config.
  • do not use RequireJS multiversion support/contexts.
  • do not use require.toUrl() or require.nameToUrl().
  • do not use packages/packagePaths config. If you need to use packages that have a main property, volo can create an adapter module so that it can work without this config. Use the amdify add command to add the dependency to your project.

What is supported:

  • dependencies with relative IDs.
  • define('id', {}) definitions.
  • define(), require() and requirejs() calls.
  • loader plugins that can inline their resources into optimized files, and can access those inlined resources synchronously after the optimization pass. The text and CoffeeScript plugins are two such plugins.

Download

Latest release

Usage

Download the RequireJS optimizer.

Download the current release of almond.js.

Run the optimizer using Node (also works in Java):

node r.js -o baseUrl=. name=path/to/almond include=main out=main-built.js wrap=true

This assumes your project's top-level script file is called main.js and the command above is run from the directory containing main.js. If you prefer to use a build.js build profile instead of command line arguments, this RequireJS optimization section has info on how to do that.

wrap=true will add this wrapper around the main-built.js contents (which will be minified by UglifyJS:

(function () {
    //almond will be here
    //main and its nested dependencies will be here
}());

If you do not want that wrapper, leave off the wrap=true argument.

These optimizer arguments can also be used in a build config object, so it can be used in runtime-generated server builds.

Triggering module execution

As of RequireJS 2.0 and almond 0.1, modules are only executed if they are called by a top level require call. The data-main attribute on a script tag for require.js counts as a top level require call.

However with almond, it does not look for a data-main attribute, and if your main JS module does not use a top level require() or requirejs() call to trigger module loading/execution, after a build, it may appear that the code broke -- no modules execute.

The 2.0 RequireJS optimizer has a build config, option insertRequire that you can use to specify that a require([]) call is inserted at the end of the built file to trigger module loading. Example:

node r.js -o baseUrl=. name=path/to/almond.js include=main insertRequire=main out=main-built.js wrap=true

or, if using a build config file:

{
    baseUrl: '.',
    name: 'path/to/almond',
    include: ['main'],
    insertRequire: ['main'],
    out: 'main-built.js',
    wrap: true
}

This will result with require(["main"]); at the bottom of main-built.js.

Exporting a public API

If you are making a library that is made up of AMD modules in source form, but will be built with almond into one file, and you want to export a small public API for that library, you can use the wrap build config to do so. Build config:

{
    baseUrl: '.',
    name: 'path/to/almond',
    include: ['main'],
    out: 'lib-built.js',
    wrap: {
        startFile: 'path/to/start.frag',
        endFile: 'path/to/end.frag'
    }
}

Where start.frag could look like this:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        //Allow using this built library as an AMD module
        //in another project. That other project will only
        //see this AMD call, not the internal modules in
        //the closure below.
        define([], factory);
    } else {
        //Browser globals case. Just assign the
        //result to a property on the global.
        root.libGlobalName = factory();
    }
}(this, function () {
    //almond, and your modules will be inlined here

and end.frag is like this:

    //The modules for your project will be inlined above
    //this snippet. Ask almond to synchronously require the
    //module value for 'main' here and return it as the
    //value to use for the public API for the built file.
    return require('main');
}));

After the build, then the built file should be structured like so:

  • start.frag
  • almond.js
  • modules for your lib, including 'main'
  • end.frag

License

MIT

Code of Conduct

jQuery Foundation Code of Conduct.

Common errors

Explanations of common errors:

incorrect module build, no module name

In almond 3.0.0 and earlier, this would show up as "deps is undefined", where this line is mentioned:

if (!deps.splice) {

In 3.0.1+ the error is explicitly: "incorrect module build, no module name".

This means that there is a define()'d module, but it is missing a name, something that looks like this:

define(function () {});
//or
define([], function () {});

when it should look like:

define('someName', function () {});
//or
define('someName', [], function () {});

This is usually a sign that the tool you used to combine all the modules together did not properly name an anonymous AMD module.

Multiple modules built into a single file must have names in the define calls. Otherwise almond has no way to assign the module to a name key for use in the code.

The fix is to use a build tool that understand AMD modules and inserts the module IDs in the build. The requirejs optimizer is a build tool that can do this correctly.

x missing y

It means that module 'x' asked for module 'y', but module 'y' was not available.

This usually means that 'y' was not included in the built file that includes almond.

almond can only handle modules built in with it, it cannot dynamically load modules from the network.

No y

It means that a require('y') call was done but y was not available.

This usually means that 'y' was not included in the built file that includes almond.

almond can only handle modules built in with it, it cannot dynamically load modules from the network.

How to get help

Contributing

Almond follows the same contribution model as requirejs and is considered a sub-project of requirejs.

almond's People

Contributors

antris avatar cstickel avatar goldibex avatar jhwohlgemuth avatar jorrit avatar jrburke avatar kkirsche avatar kondi avatar nathankleyn avatar ryanflorence avatar taoklerks avatar tomfuertes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

almond's Issues

Almond timing issue page load

I'm essentially using RequireJS to simplify development and the build process. The released version of my JS library will all be included in one file and therefore doesn't really need an AMD loader.

I've tried swapping out the full blown RequireJS during optimization with Almond. It is nice because it is so small. However, when I use the includeRequire option as part of the RequireJS optimization, the dependencies aren't immediately available at page load.

For instance, if I use JQuery's page load shortcut $(function() { }), the modules for whatever reason haven't been executed yet even though the require call is embedded within my main JS file. If I then use the console window in Chrome to see if the modules are loaded they have indeed been loaded, but presumably after page load has been fired.

If I use full blown RequireJS this behavior does not happen.

Thanks for your help in advance!

Empty factory function causes "Missing" error

define('a', function () {});
define('b', ['a'], function () {});
define('c', ['a'], function () {});

Will generate a "c missing a" error. It is because the undefined value is not set on defined when exports is not in play.

Jade-runtime breaks almond

I'm using almond by first time, everything is right but your "deps is undefined" isn't working as I expected.

Specifically I can't change the jade-runtime (even other) code since its installed through bower, so, I changed this line on almond and everything is working properly.

if (deps && !deps.splice) {

What can I do?

I think this checking is necessary, I can't spend time thinking about how hacking this on my remote building/CI process.

Advantage over RequireJS

It would seem that the main benefit Almond has over RequireJS is the size, however with minified RequireJS standing at 14.8 kB only, there isn't really much size that'd be saved.

On the other hand Almond imposes many restrictions, including losing the ability to load dependencies only on demand - which could potentially decrease the initial evaluation time of the script largely if done right.

So what's the real benefit of using Almond over RequireJS?

Missing dependency

Hi!

I use RequireJS optimizer to build my project ant its modules and faced some strange behavior:

// Built code
define('foo/bar', [...], function () { ... });
define('foo', ['./bar'], function () { ... });

So when I call

require('foo');

I get

Error: foo missing bar

Bug?: Almond won't resolve a relative require with double-dot notation

Hello @jrburke. Thanks for making almond. I just used it to make a requirejs-less build of:
http://gobengo.github.com/streamhub-backbone/

I may have discovered a bug though. If my build uses the 'namespace: "MYNS"' build config and I try to do this:

var a = require('../folder/imported');

, then the build finishes fine, but when I run the app I see:

Uncaught Error: No ../folder/imported

I made a repo that shows that this works without the namespace setting:
gobengo/almond-namespace-bug@bcfeec6
But not with it:
gobengo/almond-namespace-bug@f8ae11f

Any ideas? Thank you!

Masonryjs

Hi there

For some reason it seems impossible to use Almond to compile RequireJS when using MasonryJS and a simple onloadJS.

My HTML header looks like this:

<script src="web/require.js" type="text/javascript"></script> <script type="text/javascript"> require.config ({ baseUrl: '../WebAppTest/web/js', }); require (['onload'], function () { document.cookie='resolution='+Math.max(screen.width,screen.height)+("devicePixelRatio" in window ? ","+devicePixelRatio : ",1")+'; path=/'; }) </script>

OnloadJS defines MasonryJS as a dependency:

define(['masonry'], function () {
var wall = new Masonry( document.getElementById('photos'), {
columnWidth: function( containerWidth ) {
return containerWidth / 3;
}
});
});

Finally, MasonryJS defines RequireJS's domReady as a dependency:

define.unordered = true;
define(['domReady!'], function () {
/**
* Vanilla Masonry v1.0.04

...all masonry code

return window.Masonry;

});

If I use AlmondJS to replace RequireJS (once compiled) the assets (in my case photos) appear on top of each other which would indicate that Masonry is not running when the images are completely downloaded.

Please let me know if you want an example for this.

Many thanks in advance
Amy

almond + coffee script

In the readme it is said, that almond supports plugins (like text and cs), but then the recommended use case is to bundle everything into one file and inline plugin resources, and stub out actual plugins, which means there is actually no need for "plugin support", because when you say require(["cs!foo"]) it gets the code after define(["cs!foo"]...) and doesn't care about cs plugin.

So if I have all my modules written in coffee, and I've split them into two: first and second (modules in r.js build.js), where second is required dynamically on user interaction, how am I supposed to do it?

If I use something like require(['cs!second'], function(second) {..}), then it will search for cs plugin, which in turn will download coffee file, which is not optimal for production. I guess using a javascript bootstrap file for each module (in r.js) would solve that problem. But then I need full blown requirejs just for prepending baseUrl and fetching a script (because almond can't fetch).

Simulate async callback makes main require asynchronous, with no way to suppress it

I ended up commenting out these lines beginning at 293:

    //Simulate async callback;
    //if (forceSync) { // LES: we need this to be synchronous, but there is no way to force it using r.js insertRequire config option; this is a workaround; i'm not sure why almond has this branch in here.
        main(undef, deps, callback, relName);
    //} else {
    //    setTimeout(function () {
    //        main(undef, deps, callback, relName);
    //    }, 15);
    //}

(this code is inside this function):

    requirejs = require = req = function (deps, callback, relName, forceSync) {

The insertRequire option of the optimizer script (r.js) does not allow passing the forceSync parameter. For a use case, I needed to execute everything synchronously in the main module until I have bootstrapped because a script included by another party needs some initialization stuff I export there.

The hack above works and didn't seem to break anything, but I was wondering if someone here would know exactly why the above hack is a bad idea?

The version of almond.js I downloaded was 0.1.2 .

Thanks!

Cannot read property 'splice' of undefined

After run the optimizer, the code is built correctly without errors.
But, in browser, the compiled code throws a TypeError:

Uncaught TypeError: Cannot read property 'splice' of undefined 

Config options (i'm building in node, requirejs 1.0.8):

var config = {
    baseUrl        : './all/app/public/js',
    name           : 'lib/almond',
    include        : 'main',
    optimize       : 'none',
    mainConfigFile : './all/app/public/js/main.js',
    out            : 'all/app/public/js/production.js'
};
requirejs.optimize(config, function () { ... })

So, I changed the almond.js file in line 259 from:

if (!deps.splice) {
    //deps is not an array, so probably means
    //an object literal or factory function for
    //the value. Adjust args.
    callback = deps;
    deps = [];
}

to:

if (deps && !deps.splice) { ... }

After this change, the code is working perfectly.

Is this change safe?

Cannot read property 'splice' of undefined when using store.js

Store.js defines itself by passing the store object:

if (typeof module != 'undefined') { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { this.store = store }

This means that in the almond.js code the store object is passed for 'name' and deps and callback are undefined:

define = function (name, deps, callback) {

    //This module may not have dependencies
    if (!deps.splice) {
        //deps is not an array, so probably means
        //an object literal or factory function for
        //the value. Adjust args.
        callback = deps;
        deps = [];
    }

    if (define.unordered) {
        waiting[name] = [name, deps, callback];
    } else {
        main(name, deps, callback);
    }
};

This results in the error:
Cannot read property 'splice' of undefined

Let me know if you need the full javascript file and I can email it.

almond + i18n

I'm adding NLS support to Orion (textview/editor), see https://bugs.eclipse.org/bugs/show_bug.cgi?id=369869

I have found a small problem, the i18n plugin calls a req.mixin method that is not part of almond
I was able to workaround this easily by copying the mixing from require.js to almond.js.

On a side note, since almond does not support any dynamic loading, all nls files need to be included either in the html file or during compile time.

require()'ing a missing dependency returns null instead of throwing

From the AMD spec: https://github.com/amdjs/amdjs-api/wiki/require

Under "require(String)" is the note:

It MUST throw an error if the module has not already been loaded and evaluated.

Currently, it seems to return null. I'd actually prefer that to be the "standard", but since other require()s do throw errors, I think almond should also.

Bonus, it would be awesome to get a nice exception message for this:

Module 'xyz' not defined, but load attempted from module 'abc'

Personally, I'd just throw that message string (not bother with an "error object"). I consider this to be a development time error, so it doesn't need to be the spec-iest thing around, just useful.

i18n Locale config not taken into account with Almond

Hi,

I am trying to use i18n with Almond.
My goal is to package all the i18n files into the main JS file and tell requireJS which one to use at runtime and avoid extra http request to fetch tiny i18n files (my localization files are realy small and i need to support only few languages)

require.config({
locale : getQueryString('locale','fr-fr'),
})

require.([
'order!custom/component/fan/nls/all', // (1)- make sure languages are preloaded as part of the build optimization
'order!custom/component/fan/nls/fr/all', // (2) - make sure languages are preloaded as part of the build optimization
'i18n!custom/component/fan/nls/all' // choose which bundle to load
],
function(DUMMY, DUMMY, i18nText){
[....]
});

it looks like the almond does not pass the locale config to i18n plugin,
I have changed a bit almond to do that @see at https://github.com/sebcante/almond/blob/master/almond.js.

(1) and (2) is the only way i found to make the optimizer preload i18n bundles.

let me know if you feel this could be incorporated or their might be a better way to do this

cheers

-seb

using no deps on define() does not get you require/exports/module for free

From the AMD spec: https://github.com/amdjs/amdjs-api/wiki/AMD

Under the heading hierarchy "API Specification" -> "define() function" -> "dependencies", is the following note:

The dependencies argument is optional. If omitted, it should default to ["require", "exports", "module"]. However, if the factory function's arity (length property) is less than 3, then the loader may choose to only call the factory with the number of arguments corresponding to the function's arity or length.

This doesn't seem to work with almond; if I use:

   define("a", function(require,exports,module){...})

all of require, exports, and module are null-ish, but if I use

   define("b", ["require","exports","module"], function(require,exports,module){...})

then things seem to work correctly

Order of define calls is significant

The AMD wiki states that the order of define calls should not be significant. With almond the following example will run as expected...

define('a', function() {
    return {
        name: 'a' 
    }; 
});

define('b', ['a'], function(a) {
    return {
        a: a
    }; 
});

require(['b'], function(b) {
    console.log(b.a.name); // Will output 'a'
});

However with the order of define calls reversed the module factory function for 'b' is given undefined for the value of module 'a'.

define('b', ['a'], function(a) {
    return {
        a: a
    }; 
});

define('a', function() {
    return {
        name: 'a' 
    }; 
});

require(['b'], function(b) {
    console.log(b.a); // undefined
    console.log(b.a.name); // throws error
});

Is this correct behavior? In my use case we're just including a bunch of bundled scripts in which it's difficult to ensure the order of defines. However all will be executed before the first require.

Great project - thanks for putting it out!

has no method 'toUrl'

I'm using the sugar syntax to load templates into my views:

...
var template = require('text!templates/toolbar/toolbar.html')

Everything works fine, but when I run the r.js optimizer I get the error

TypeError: Object function () {
        //A version of a require function that passes a moduleName
        //value for items that may need to
        //look up paths relative to the moduleName
        return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
    } has no method 'toUrl'

setTimeout to async-ify require([]) form's choice of 15ms sounds overkill

The setTimeout used for require(['blah']) (as compared to require('blah') which is immediate) seems odd in a loader that is presumably used to try and minimize startup latency. While using a postMessage hack for a zero timeout is probably the most reliable solution (http://dbaron.org/log/20100309-faster-timeouts), just using a timeout of zero can also work in non-recursive cases. Specifically, I think at least Firefox will honor a setTimeout(0) if it is not called from within an existing setTimeout callback. (That is obviously done to avoid buggy/ill-conceived code from doing setTimeout(0) and dominating the event loop.)

If there is intent, I think a comment should be added.

The missing dependency throw does not create an Error object

https://github.com/jrburke/almond/blob/master/almond.js#L184 does:

throw name + ' missing ' + depName;

If it throws an actual Error object, then Firefox's JS console does a less crappy job of reporting the error. Specifically, as it is now, the Error can show up as:

JavaScript error: , line 0: uncaught exception: undefined missing path

But with Error, we get:

JavaScript error: http://email.gaia.localhost:8080/js/gaia-email-opt.js, line 186: Error: undefined missing path

I think the specific failure there is more misleading because it's secondary fallout of a different missing dependency that makes more sense without context:

throw name + ' missing ' + depName;

If you're being really stingy on bytes, I can see why you'd keep it like it is. But then maybe you can put a comment in with the assumption it will get optimized out by the optimizer that people will surely use? :)

insertRequire=main should be sync or should have a sync option

Hi!

I want to create a public library that uses require.js and exposes a public API (for those non-require.js users).

Currently, I have to use those ugly start.frag and end.frag options, in which all I do is require('main'). However, those are not jslint'able and weird to read.

I would love to use insertRequire=main, but that would do require(['main']), which is async (and which doesn't make any sense for almond.js).

So my proposal:

  • Either a) make insertRequire=main insert a require('main')
  • or b) provide a forceSync that makes all insertRequire options sync
  • or c) provide a insertSyncRequire=main option

As this change would actually be in require.js and I'm not sure how and where insertRequire is used by different people, option b) or c) is probably the safest.

If you would consider merging it, I would try to create a patch for require.js to accept a forceSync or insertSyncRequire option. Just say what you think is best :)

Thanks in advance for your time and efforts!

Cheers,
Kosta

Uncaught ReferenceError: exports is not defined

Hi james,

I am migrating to require 2.0 and using almond. I have a couple of shim configured it is working fine when using require.js but after minification (using almond instead of require.js) it seems that something is missing :

error : Uncaught ReferenceError: exports is not defined
getGlobal does not seem exist.

here is the code created as build time

define("backbone", ["underscore","jquery"], (function (global) {
    return function () {
        var func = function () {

                            return getGlobal(exports); <-- Uncaught ReferenceError: exports is not defined

                        };
        return func.apply(global, arguments);
    }
}(this)));

This example uses the following shim

   shim:{
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['underscore', 'jquery'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        },   [...]

Version :
r.js 2.0.6
almond 0.1.4

jQuery 1.7 Breaking Almond When Optimizing To Single File

Hey James -

Ran into this weird issue while trying to use Almond to run my optimized code. Looks like jQuery breaks the optimization step somehow?

Here's the isolated test case:
http://dl.dropbox.com/u/4584460/reqtest/index.html

The error I get using example #3 from the link above is:
Uncaught TypeError: undefined is not a function

Where 'undefined' should be jQuery. This goes away if I do not try to include jQuery (example #4).

FWIW, I'm also seeing this an error when I try to package my optimized code into a single file using require itself (example #2).
Uncaught ReferenceError: define is not defined

Running the unoptimized modules works fine (example #1).

I think I have my build configured properly but I'm not 100% sure.

Let me know if there's any additional info you could use.

Thanks!
-matt

Node.JS / Require.JS / Almond.js compatible define

I have been using the following define structure for my Require.JS and Node.JS project. Almond.js, however, fails. Any way to make it Almond.JS compatible as well?

var DOMParser;
var XMLSerializer;
({
    define: typeof define === "function" ? define : function(A, F) {
        module.exports = F.apply(null, A.map(require));
        DOMParser = require('xmldom').DOMParser;
        XMLSerializer = require('xmldom').XMLSerializer;
    }
 }).
define([], function() {

});

npe on deps.splice

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {

shouldn't that be...

        if (!deps || !deps.splice) {

Problem with paths no require config

I'm trying to build a project, and i have a complex structure from js files

my require config

require.config({
    waitSeconds: 30,
    packages: [
        "libs/jquery/", 
        "libs/underscore/",
        "libs/backbone/",
        "libs/backbone/plugins/",
        "libs/requirejs/",
        "libs/flowplayer/",
        "libs/jquery/plugins/"
    ],
    paths: {
        'jquery': 'libs/jquery/jquery-1.9.1',
        'underscore': 'libs/underscore/underscore',
        'backbone': 'libs/backbone/backbone',
        'loader': 'libs/backbone/loader',
        'backbone-queryparams': 'libs/backbone/plugins/backbone.queryparams',
        'bootstrap': 'libs/bootstrap/bootstrap',
        'text': 'libs/requirejs/text',
        'flowplayer': 'libs/flowplayer/flowplayer',
        'jquery-ui': 'libs/jquery/plugins/jquery-ui-1.10.1.custom',
        'jquery.ui.widget': 'libs/jquery/plugins/jquery.ui.widget',
        'iframe-transport': 'libs/jquery/plugins/jquery.iframe-transport',
        'fileupload': 'libs/jquery/plugins/jquery.fileupload',
        'meio-mask': 'libs/jquery/plugins/jquery.meio.mask',
        'underscore-ead': 'libs/underscore/underscore-ead',
        'templates': '..'
    },
    shim: {
        'backbone': {
            deps: ['jquery', 'underscore'],
            exports: 'Backbone'
        },
        'backbone-queryparams': ['backbone'],
        'jquery-ui': ['jquery'],
        'iframe-transport': ['jquery'],
        'fileupload': ['jquery', 'jquery.ui.widget', 'iframe-transport']
    }
}); 

require(['app'], function(App) {
    App.initialize();
}, function (err) {
    $("#box-loader").addClass("hide");
    $('#content').append("<p class='alert alert-error'>Desculpe, ocorreu algum problema e não estamos conseguindo completar sua requisição. Por favor, tente acessar novamente, ou <a href='' onClick=\"window.location;$('#content').remove();\">clique aqui</a> para recarregar a página.</p>");
});

when I try I get this error because almond cant recognize jquery as name space from a path and try to find jquery
console log

Tracing dependencies for: almond
Error: ENOENT, no such file or directory '/tmp/tmplBGTl0/javascripts/jquery.js'
In module tree:
    main
      app

Error: ENOENT, no such file or directory '/tmp/tmplBGTl0/javascripts/jquery.js'
In module tree:
    main
      app

Ps: I using django-require project to do this https://github.com/etianen/django-require

"The modules must be optimized in order"

From the README file:

    The modules must be optimized in order, so common dependencies, 
    modules with no dependencies are first in the file.

Is this a limitation of almond, or a semantic issue with AMD? When I ran into this problem (my modules were not listed in pre-req happy order), debugging it, I could see that the define() calls actually seemed to be loading the module as well. Is that just an 'optimization' for almond, or the way AMD is supposed to work?

If it's a semantic of AMD that modules are loaded during define(), I guess AMD isn't the tool I'm looking for. But if it's just an optimization for almond, that can be fixed.

Here's my use case. I have a wad of AMD modules. I have almond. I want to package all that up in a single file, quickly. Basically using cat. Include this file in an .html file, and then require() away to get to the modules.

Unfortunately, getting this to work would require me to append the AMD modules in pre-req order, which is something I don't want to have to deal with. This is needed for my continuous dev build, so using an optimizing build isn't the right tool; again, think cat as the build tool of choice here.

relative dependencies no longer work in 0.1

Reported by Jasper Palfree on the requirejs mailing ilst.

Fiddle:
http://jsfiddle.net/wellcaffeinated/9knfL/1/

Code snippet:

define('fu/a', [], function(){
    log('factory for a');
});

define('foo/bar/c',['../../fu/a'], function(){
    log('factory for c');
});

define('foo/b',['./bar/c'], function(){
    log('factory for b');
});

define('main', ['./foo/b'], function(){
    log('factory for main');
});

require(['main'], function(){
    log('factory for main');
});

Only accept the first define call

Right now, almond will let the second of two define() calls for the same ID win, which is different from what requirejs allows, and different from expectations in general.

undefined module not throwing exception when require()'d

I suspect this may only be a problem when define.unordered == true.

If you invoke require() for a module which has not been define()'d, a null is currently returned for the module exports. An exception should be thrown instead.

Leaving out jQuery

I'm trying to create an optimized version of my jQuery plugin, but I want to leave out jQuery itself, because most users will already have it loaded through a <script> tag.

My main.js file looks like this:

require.config({
  paths: {
    'jquery'      : '../../../vendor/jquery-1.7.1/jquery'
  , 'tween'       : '../../../vendor/tween-r5/tween'
  , 'three'       : '../../../vendor/three-r47/three'
  , 'utils'       : 'jquery.utils'
  , 'superplugin' : 'jquery.superplugin'
  }
});

require(['jquery', 'superplugin'], function($) {
  $('.superplugin').superplugin();
});

And my build.js file (invoked through node) looks like this:

var requirejs = require('requirejs')

// Default configs.
var baseConfigs = {
  scripts : {
    baseUrl : 'src/scripts/js'
  , optimize : 'none'
  , wrap : true

  , paths : {
      'jquery'      : 'empty:'
    , 'tween'       : '../../../vendor/tween-r5/tween'
    , 'three'       : '../../../vendor/three-r47/three'
    , 'utils'       : 'jquery.utils'
    , 'superplugin' : 'jquery.superplugin'
    }

  , name : '../../../vendor/almond-0.0.3/almond'
  }
, styles : {
    baseUrl : 'src/styles/css'
  , optimizeCss : 'standard'
  }
}

// Actual configs
var configs = {
  scripts : [
    {
      include : ['main']
    , out     : 'build/jquery.superplugin.js'
    }
  ]
, styles : [
    {
      cssIn : 'src/styles/css/superplugin.css'
    , out   : 'build/superplugin.css'
    }
  ]
}

// Extend a given object with all the properties in passed-in object(s).
function extend(target) {
  Array.prototype.slice.call(arguments, 1).forEach(function (source) {
    for (var prop in source) {
      target[prop] = source[prop]
    }
  })
  return target
}

// Merge the actual configs with the base configs, and pass them to the
// optimizer.
for (var type in configs) {
  configs[type].reduceRight(function (prevConfig, currentConfig) {
    return function (report) {
      console.log(report)
      requirejs.optimize(extend(currentConfig, baseConfigs[type]), prevConfig)
    }
  }, function (report) {
    console.log(report)
  })('Optimizing ' + type + ' ...')
}

The file superplugin.js gets generated correctly, without jQuery, but with all the other dependencies:

(function () {

var requirejs, require, define;
(function (undef) {

...

require.config({
  paths: {
    'jquery': '../../../vendor/jquery-1.7.1/jquery',
    'tween': '../../../vendor/tween-r5/tween',
    'three': '../../../vendor/three-r47/three',
    'utils': 'jquery.utils',
    'superplugin': 'jquery.superplugin',
  }
});

require(['jquery', 'superplugin'], function($) {
  $('.superplugin').superplugin();
});

define("main", function(){});
}());

When testing this in a browser, I use the following HTML:

<!doctype html>
<html lang="en">
  <head>

    <meta charset="utf-8" />
    <title>Superplugin</title>

    <link href="../build/superplugin.css" rel="stylesheet" />

  </head>

  <body>

    <section class="superplugin">
      ...
    </section>

    <script src="../vendor/jquery-1.7.1/jquery.js"></script>
    <script src="../build/superplugin.js"></script>

  </body>
</html>

But it throws out the following error:

Uncaught utils missing jquery

So, even though jQuery is included in the page through a <script> tag, almond doesn't seem to know of its existence...

Is there a way to optimize my plugin without jQuery, but everything still working if users include jQuery on their own?

error in compiled file

I get:

TypeError: 'undefined' is not a function (evaluating 'd.nameToUrl(a,null)')

I build the app using requirejs 1.0.3 and almond 0.0.3

node RequireJS/r.js -o baseUrl=../www/_js name=almond include=app out=../build/_js/almond.js

i include the app: <script src="_js/almond.js"></script>

are there any other things to take not when using almond?

thx in advance

Clarify readme

Hi

There are some parts of the readme that confuse me. Could you clarify them either here or in the readme file itself?

Restrictions

  • do not use packages/packagePaths config.

Does this mean I can't use any packages at all or just not use the package parameter when optimizing with r.js?

Usage

Run the optimizer using Node (also works in Java):
node r.js -o baseUrl=. name=path/to/almond.js include=main out=main-built.js wrap=true

How do I use Almond with an app.build.js file?
I.E. how do I transform node ../../r.js -o app.build.js (given under http://requirejs.org/docs/optimization.html#wholeproject) into the right command using almond.js?

Probably I wouldn't ask these questions if I was better at Node. Still, clear (and a bit of beginner) documentation is as important as good code to me.

insertRequire not executing module

Hi there,

Sorry in advance if I put this in the wrong repo (r vs almond).

In my build.js I've added insertRequire: ["a"] which then puts at the end of the output require(["a"]);.

Everything in the output looks fine but nothing actually executes on the page. I found that if I directly edit the output to be either require('a'); or require(['a'], function(){}); it will work as expected.

Any ideas?

Edit: Here is a simple demo of the setup I'm using, including output file. https://github.com/dylanharrington/quicky
generated with node r.js -o app.build.js optimize=none

Having a version of almond.js with unordered set to true by default

Hi,

I really like almond.js and I want to use it. However I have the situation that all scripts in the application are combined in an unordered way. It is only guaranteed that almond.js comes before the normal scripts. What I cannot guarantee is that my script setting the define.unordered option to true comes after including almond.js but before the modules.

It would be best if there was some way to have define.unordered set to true by default. But since I don´t want to locally modify the library I wanted to ask if you could add another version of almond.js like almond.unordered.js which is the same as almond but with the option set to true.

This way I wouldn´t have any problems with updating almond.js at any point.

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.