GithubHelp home page GithubHelp logo

almond's Introduction

RequireJS

RequireJS loads plain JavaScript files as well as more defined modules. It is optimized for in-browser use, including in a Web Worker, but it can be used in other JavaScript environments, like Rhino and Node. It implements the Asynchronous Module API.

RequireJS uses plain script tags to load modules/files, so it should allow for easy debugging. It can be used simply to load existing JavaScript files, so you can add it to your existing project without having to re-write your JavaScript files.

RequireJS includes an optimization tool you can run as part of your packaging steps for deploying your code. The optimization tool can combine and minify your JavaScript files to allow for better performance.

If the JavaScript file defines a JavaScript module via define(), then there are other benefits RequireJS can offer: improvements over traditional CommonJS modules and loading multiple versions of a module in a page. RequireJS also has a plugin system that supports features like i18n string bundles, and text file dependencies.

RequireJS does not have any dependencies on a JavaScript framework.

RequireJS works in IE 6+, Firefox 2+, Safari 3.2+, Chrome 3+, and Opera 10+.

Latest Release

License

MIT

Code of Conduct

jQuery Foundation Code of Conduct.

Directories

  • dist: Scripts and assets to generate the requirejs.org docs, and for generating a require.js release.
  • docs: The raw HTML files for the requirejs.org docs. Only includes the body of each page. Files in dist are used to generate a complete HTML page.
  • tests: Tests for require.js.
  • testBaseUrl.js: A file used in the tests inside tests. Purposely placed outside the tests directory for testing paths that go outside a baseUrl.
  • updatesubs.sh: Updates projects that depend on require.js Assumes the projects are siblings to this directory and have specific names. Useful to copy require.js to dependent projects easily while in development.

Tests

This repo assumes some other repos are checked out as siblings to this repo:

git clone https://github.com/requirejs/text.git
git clone https://github.com/requirejs/i18n.git
git clone https://github.com/requirejs/domReady.git
git clone https://github.com/requirejs/requirejs.git

So when the above clones are done, the directory structure should look like:

  • domReady
  • i18n
  • text
  • requirejs (this repo)

You will need to be connected to the internet because the JSONP and remoteUrls tests access the internet to complete their tests.

Serve the directory with these 4 siblings from a web server. It can be a local web server.

Open requirejs/tests/index.html in all the browsers, click the arrow button to run all the tests.

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

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

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?

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.

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!

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

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).

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) {

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?

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'

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.

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

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

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

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.

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? :)

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.

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.

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.

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!

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');
});

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.

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.

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

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() {

});

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

"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.

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?

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

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

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!

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!

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.

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.