GithubHelp home page GithubHelp logo

requirejs / requirejs Goto Github PK

View Code? Open in Web Editor NEW
12.9K 12.9K 2.4K 14.42 MB

A file and module loader for JavaScript

Home Page: https://requirejs.org/

License: Other

Shell 0.48% JavaScript 67.96% HTML 31.56%

requirejs'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.

requirejs's People

Contributors

adamth avatar ahadb avatar altearius avatar amylo avatar andresmrm avatar anishathalye avatar archive avatar arian avatar avindra avatar benvinegar avatar brettz9 avatar brianpeiris avatar clmath avatar conradz avatar evverx avatar explunit avatar fitzgen avatar harshadsabne avatar ivaylo5ev avatar jrburke avatar karlwestin avatar kriszyp avatar lykahb avatar mightyiam avatar mjomble avatar neonstalwart avatar nikolas avatar normanzb avatar slexaxton avatar yuyokk 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  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

requirejs's Issues

Using order! plugin causes files to be ignored by the build system

Thanks for this awesome library.

The order plugin is very useful for including libraries that are not defined as modules (e.g. jQuery, jQuery UI, Less.js, Ext.js...) and allows extremely quick first step migration to RequireJS. However you don't get the benefit of a single file build because the RequireJS build system ignores these files.

require([
  'order!a',
  'order!b',
  'order!c'
], function() {
});
/path/to/requirejs/build/build.sh name=main out=main-built.js baseUrl=. includeRequire=true

Result: a.js, b.js and c.js are not included in main-built.js. But work loading separately in the browser.
Expected result: a.js, b.js and c.js are included in main-built.js.

At the very least this should be made obvious in the documentation, and would be awesome if there is a possible fix. I've been trying to debug jslibs/build.js but can't work it out yet. Any hints would also be appreciated.

Consider file:// support for text! plugin

David Snopek brought up an issues with file::// URLs and the text! plugin on the discussion list.

Figure out a way to support it better inline. A file:// check could be done for IE to get it to work and falling back to ActiveX-based XHR. Firefox probably just needs documentation on the pref to set, need to check webkit and Opera for a possible solution.

jslint errors with current download of allplugins-require.js

I think you need to add white: false to the jslint comment.

Otherwise you get:
Verifying allplugins-require.js with JsLint
Problems detected
Lint at line 383 character 25: Expected 'if' to have an indentation at 13 instead at 25.
if (s.plugins.newContext) {
Lint at line 517 character 21: Expected '}' to have an indentation at 9 instead at 21.
}
Lint at line 526 character 17: Expected 'if' to have an indentation at 9 instead at 17.
if (pluginPrefix) {
Lint at line 570 character 17: Expected 'plugins' to have an indentation at 9 instead at 17.
plugins: {
Lint at line 761 character 25: Expected 'callPlugin' to have an indentation at 13 instead at 25.
callPlugin(pluginPrefix, context, {
Lint at line 765 character 21: Expected '}' to have an indentation at 9 instead at 21.
} else {
Lint at line 775 character 49: Expected 'callPlugin' to have an indentation at 25 instead at 49.
callPlugin(dep.prefix, context, {
Lint at line 779 character 45: Expected '}' to have an indentation at 21 instead at 45.
} else {
Lint at line 1277 character 25: Expected 'modify' to have an indentation at 13 instead at 25.
modify: makeContextModuleFunc("modify", contextName, moduleName),
Lint at line 1278 character 25: Expected 'def' to have an indentation at 13 instead at 25.
def: makeContextModuleFunc("def", contextName, moduleName),
Lint at line 1537 character 25: Expected 'rePkg' to have an indentation at 13 instead at 25.
rePkg = /(allplugins-)?require.js(\W|$)/i;
Lint at line 1539 character 21: Expected '}' to have an indentation at 9 instead at 21.
}

build failure when returning an object from define

if i have a file with this kind of format, the build fails
(function () {
var foo = {
bar: 'baz'
}

    define('foo', [], foo);
}());

the output from the build is
Tracing dependencies for: foo
js: "/homes/staff/ben/git/requirejs/build/jslib/requirePatch.js#143(eval)", line 1: uncaught JavaScript runtime exception: ReferenceError: "foo" is not defined.
at /homes/staff/ben/git/requirejs/build/jslib/requirePatch.js#143(eval):1

makeRequire excludes require.def

I noticed require.def doesn't in a new require context
require({context:'new context'},['require'],function(require){
console.log( require.def ); // undefined WaH?!
}

This used to work in 0.15.0:
https://github.com/jrburke/requirejs/blob/0.15.0/require.js#L1366

Is there a reason why this was removed?

I've been using feature for unit testing so tests would be isolated in their on require context AND require.def could "inject" spy/mock modules.
https://github.com/peterwmwong/cell/blob/master/test/unit/cell/CellTest.coffee#L6

Thanks.

Anonymous Modules in subdirectories fail

Not sure how the spec does/should support this, but if I have a.js:

require.def(function (require, module, exports) {
    var b =  require("sub/b");
});

And a module in a subdirectory (sub/b.js):

require.def(function (require, module, exports) {
    exports.f = function () {};
});

When requiring, "a", Firefox/Win 3.6.10 gives me the error:

exports is undefined
exports.f = function () {};

It works fine if I have:

require.def(["require", "module", "exports"], function (require, module, exports) {
    exports.f = function () {};
});

in sub/b.js.

JS error (OSX FF 3.5+)

OSX FF 3.5+, firebug reports.

Index or size is negative or greater than the allowed amount" code: "1
for (i = scripts.length - 1; (script = scripts[i]); i--) {
(line 1056)

Bug in i18n Module

I'm attempting to use the i18n plugin and I'm getting a couple of different errors with it.

In Chrome:

Uncaught TypeError: Cannot read property 'en-us' of undefined
Uncaught TypeError: Cannot read property 'warnOnClose' of undefined

In Firefox

Error: bundle is undefined
Source File: http://localhost:3000/javascripts/roster_1.1/require/i18n.js
Line: 76

My translation file:

require.def("i18n!nls/messages",
[{
"root": {
"red": "red",
"blue": "blue",
"green": "green",
"warnOnClose": "Found warn on close"
}
}]
);

And I'm calling it with:

"i18n!nls/messages",

As far as I can tell everything is working correctly. Placing an alert("found'); in the translation file shows it is being parsed by required.js. I don't think I'm missing anything obvious and I've been able to use the regular module include and text include without any problems.

I'm using the require.js file and its plugins cloned from Github. I've tried both the minified file and the regular unpacked version, both give the same error. I'm also using jQuery on the page.

Sam

evt.target vs event.currentTarget

Hi,

I came across a little bug with firefox 2.0.0.13.

Throws error in require.onScriptLoad. node.getAttribute is not a function.

Replacing evt.target with evt.currentTarget in same function fixed it.

Thanks,
James

Unexpected behavior of require('') or modules containing strings with require('')

https://github.com/jrburke/requirejs/blob/a1727c494a0b32546fbd1b6727a12606ed8a82be/require.js#L1221

//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies.
callback
  .toString()
  .replace(commentRegExp, "")
  .replace(cjsRequireRegExp, function (match, dep) {
     deps.push(dep);
});

WOW. So modules like this don't work:

define(function() {
   var mooby;
   mooby = {};
   define('Mooby', function() {
     return mooby;
   });
   console.log( mooby === require('Mooby') );  // false, WAH?!
});

... because require('Mooby') get executed when the module is loaded, before the module is initialized and define('Mooby') occurs.

I know this is rare, but this was how I stumbled upon the issue

define(function() {
   test( 'Make sure require("cell!") works', function(){...} );
});

... so even though require is PART OF A STRING it's trying to load the dependency.
FUN!

Was this synchronous flavor of require() for node integration?

Thanks.

i18n build failure when comments used in define call

try changing requirejs/tests/i18n/nls/en-us-surfer/colors.js like this

define(
//begin v1.x content
{
    red: "red, dude"
});

the comment might look familiar to you :)

then build the requirejs/build/tests/i18n.build.js profile and look at requirejs/build/tests/builds/i18n/testModule.js - the important part is the last ~15 lines

define(
//begin v1.x content
{
    red: "red, dude"
});
define("nls/en-us-surfer/colors", function(){});
define('i18n!nls/colors',{
    "root": {
        red: "red",
        blue: "blue",
        green: "green"
    },
    "en-us-surfer": true,
    "fr": true
});
//A sample module to use in the i18n build test.
define('testModule',["i18n!nls/colors"], function (colors) {
   var red = colors.red; 
});

the first few lines here show the problem.

inlineText, text! doesn't appear to work at build time

It appears that text! directive fails completely to include inline text at build time. It works very well during runtime in the browser, but at build time. I checked inlineText() function in optimize.js and at the end it does readFile(textPath) which fails silently. textPath is undefined because the path doesn't start with dot "." character which isn't a requirement as far as I understand.

define(['text!templates/document/header_toolbar.html'], ...

Thoughts

Hi!

  1. When require()ing multiple vanilla javascript files the resulting callback receives a bunch of undefined arguments which correspond to the return values of loaded scripts. Since require() iterates over an array, the order or callback arguments must be carefully preserved in order to not miss the value which may come from truly module being require()d. When one changes the order in require() clause, the callback arguments must be shuffled. So the idea -- to allow require() iterate over a hash and use that hash keys as names for arguments to callback function. Just a sugar, though
  2. Is there a way to mimic yepnope functionality in RequireJS? Say, by prefixing module names with yep! and so on?

TIA,
--Vladimir

after doing a build with the order plugin it still tries to load modules which are already loaded

in chrome (supportsInOrderExection is false), after doing a build, any files that were built with the order dependency will be loaded again - check the network tab. you won't see the scripts in the script or elements tab because the scripts are removed by the plugin.

also, you won't see this behavior in firefox because supportsInOrderExection is true.

the plugin architecture has changed which makes pull request 40 invalid as a fix but the bug still exists. for the branch where supportsInOrderExection is false the order plugin needs to know if the module is already loaded before it tries to load it.

note: after manually adjusting my output to counteract #52 this still happens so this is not caused by the same bug which causes #52

optimizer (build.js) gets confused by Unicode BOM

When you optimize a set of require.js modules, if the modules start with the Unicode BOM (U+FEFF proper, the bytes 0xEF,0xBB,0xBF in utf8), the parser fails to recognize the require.def calls. ( I assume it doesn't realize the BOM is whitespace and treats it as a syntax error. either way, it doesn't recognize the require.def, so it includes the whole file, then an extra require.def with an empty function. I'm not sure what this does, but it doesn't seem good, and screws up my app something fierce.

json

Hi!

Am I right that to require some JSON data I can use require(['/home?callback=define'], function(homeData){...})? If so, why Uncaught SyntaxError: Unexpected token : can be thrown?
I analyze the resource flow and see clearly a well constructed JSON is served.

TIA,
--Vladimir

Order plug-in incompatible with Firefox 4 and HTML5

RequireJS has this bit of browser sniffing:

var supportsInOrderExecution = ((window.opera && Object.prototype.toString.call(window.opera) === "[object Opera]") ||
                           //If Firefox 2 does not have to be supported, then
                           //a better check may be:
                           //('mozIsLocallyAvailable' in window.navigator)
                           ("MozAppearance" in document.documentElement.style))

Since ("MozAppearance" in document.documentElement.style) evaluates to true in Firefox 4, supportsInOrderExecution is set to true.

Then the "order" plug-in has this bit:

        require.s.skipAsync[url] = true;
        if (supportsInOrderExecution) {
            //Just a normal script tag append, but without async attribute
            //on the script.
            require([name], contextName);

That is, the code assumes that in Gecko-based browsers if .async hasn't been assigned to, script-inserted external scripts will by default execute in their insertion order.

This is not true for Firefox trunk, because script execution in Firefox changed to be HTML5-compliant on this point, and HTML5 specifies the IE/WebKit behavior of script-inserted external scripts executing as soon as they've been fetched without order guarantees.

To address the use case of loading interdependent script-inserted external scripts in parallel while executing them in a certain order, Firefox nightlies (but unfortunately not Firefox 4 beta 7) now make .async default to true for script-created scripts, but you can assign .async=false on those script-inserted external scripts that you want to maintain order among each other.

This solution was proposed by the developer of LABjs and has been proposed as a change to the HTML5 spec: http://www.w3.org/Bugs/Public/show_bug.cgi?id=11295

So concretely, I suggest making two changes:

  1. Setting supportsInOrderExecution to true also if (document.createElement("script").async) evaluates to true for forward compatibility with other browsers implementing this behavior (including future Firefox if we rename -moz-appearance to appearance at some point!). (Reportedly, the script/cache trick no longer works in WebKit nightlies since they made HTML5-compliance fixes, too.)

  2. Instead of

         if (!s.skipAsync[url]) {
            node.async = true;
        }
    

I suggest doing node.async = !s.skipAsync[url];

For more information, please see http://hsivonen.iki.fi/script-execution/

jsonp

Hi!

Sorry for posting it here -- seems jquery repo has means to post issues.

If my JSONP service returns JSON array, say define([{foo: 'bar'}]), it doesn't get parsed properly and I get [null] in response. If it returns define("data":[{foo: 'bar'}]), I get what expected.

Wonder if it's a bug or a feature.

TIA for feedback,
--Vladimir

order plugin broken after spider branch merged into master

if you make a small change to tests/order/order.html you will see a problem with using the order plugin.

change:
//Test ordering .js paths and scripts referred to without .js
["require", "order!one.js", "order!two", "order!three.js"],
function(require) {

to:
//Test ordering .js paths and scripts referred to without .js
["foo.js"],
function() {

if you check this change before (i went back to changeset 609c397) and after the spider branch merge, you will see that it used to work but now it doesn't.

strange IE8 behavior

I am using require.js to load 10 scripts. While it worked fine in FF I am getting "'undefined' is null or not an object" on line 1055 of the unmininified code. Did a little digging and it seems that at line 502: deps[i] = req.splitPrefix(outDeps[i], (name || relModuleName), context); FF reports outDeps.length as 10 and IE reports it as 11. So when IE tries that 11th loop....
I can supply more info if needed.
Thanks
GP

Is it possible to use full urls in the 'paths' configuration option?

Is it possible to make RequireJS not add a .js suffix to the URLs, refered in the paths
configuration option (assuming usage of full URLs there)?

I get URLs of static media files from Django template system. For example::

<script type="text/javascript" src="{% mediaurl 'js/jquery-ui-1.8.custom.min.js' %}">

that produces::

<script type="text/javascript" src="/appmedia/myapp/js/jquery-ui-1.8.custom.min.js">

And I want to use RequireJS to manage javascript dependences. Therefore I
transform the main template to the following::

<script type="text/javascript">
require({
  paths: {
"jquery.ui": "{% mediaurl 'js/jquery-ui-1.8.custom.min.js' %}"
  }
});
</script>
...

And any other templates became::

<script type="text/javascript">require(['jquery.ui'])</script>
...

Its cool. :) But the Django generates full URL paths to the javascript
resources, so produces the following HTML code::

<script type="text/javascript">
require({
  paths: {
"jquery.ui": "/appmedia/myapp/js/jquery-ui-1.8.custom.min.js"
  }
});
</script>

The problem is in the RequireJS which adds .js suffix to a path, therefore a
browser makes request to the not existent URL
/appmedia/myapp/js/jquery-ui-1.8.custom.min.js.js (note double .js at
the end).

Hence I am extorted to use some kind of hack to use RequireJS::

...
"jquery.ui": "{% mediaurl 'js/jquery-ui-1.8.custom.min.js' %}".replace(/\.js$/, '')

There are another misleading cases with RequireJS URL format assumption::

  /jsapi/ => /jsapi/.js 
  /jsapi?v=1.0 => /jsapi?v=1.0.js

Is it possible to make assumed URL suffix a configuration option?
Is it better to not implement any URL format assumption in the RequireJS at all?

exception thrown in module during req.exec can break module loading by leaving isCheckLoaded = true

Hypothetically speaking, I may have some code that throws when the stack looks like so:

req.execCb : 1440
req.exec : 1401
resume : 168
req.completeLoad : 753
req.onScriptLoad : 1488
(root of stack)

This hypothetically happens as the result of a dynamic require. (I required "require" and then did a require(["blah"], function (blah) { throw new Error(); }).)

Anywho, since req.exec does not protect itself against user code throwing a hypothetical exception, the code never seems to get to the "context.isCheckLoaded = false;" on line 1245.

I noticed this because I am hypothetically implementing a dynamically loaded debug UI, which, as you might expect, I hypothetically only want to use after something bad has happened, hypothetically.

requireJS with Nodejs not loading modules below top directory

Directory Structure:
/
server.js
fake.js
/web
fake.js

Module code fake.js and web/fake.js:

require.def("fake", [], function(){ 
  return{lol : 'you guise'}; 
});

Server code :

require(['sys', 'http',  "web/fake", "fake"],  function(sys, http, web_fake, fake){  
   http.createServer(function (req, res) {
   console.log(web_fake);
   console.log(fake);
}).listen(8124, "127.0.0.1");
   console.log('Server running at http://127.0.0.1:8124/');
});

Debug output:

RequireJS about to evaluate module: querystring
fileName: /Users/kevzettler/Projects/Javascript/Mordor/web/fake.js
RequireJS about to evaluate module: web/fake
Evaluating module: events
Evaluating module: sys
Evaluating module: buffer
Evaluating module: path
Evaluating module: string_decoder
Evaluating module: fs
Evaluating module: dns
Evaluating module: freelist
Evaluating module: crypto
Evaluating module: net
Evaluating module: querystring
Evaluating module: url
Evaluating module: http
Server running at http://127.0.0.1:8124/
undefined
{ lol: 'you guise' }

Tried changing the /web/fake.js to /web/fun.js and updtaing the names got similar results:

RequireJS about to evaluate module: querystring
fileName: /Users/kevzettler/Projects/Javascript/Mordor/web/fun.js
RequireJS about to evaluate module: web/fun
fileName: /Users/kevzettler/Projects/Javascript/Mordor/fake.js
RequireJS about to evaluate module: fake
Evaluating module: events
Evaluating module: sys
Evaluating module: buffer
Evaluating module: path
Evaluating module: string_decoder
Evaluating module: fs
Evaluating module: dns
Evaluating module: freelist
Evaluating module: crypto
Evaluating module: net
Evaluating module: querystring
Evaluating module: url
Evaluating module: http
Server running at http://127.0.0.1:8124/
undefined
{ lol: 'you guise' }

build.sh - $(cmd) doesn't work with older shells

at work, we use opensolaris and it doesn't support the $(cmd) variant of command substitution. this gist shows a variant of build.sh that uses backticks. i would add a pull request but the change is so small and forking, cloning, changing, pushing, ... at work is a PITA - hence the gist.

in fact, here it is inline:
#!/bin/sh

MYDIR=`cd \`dirname "$0"\`; pwd`
java -classpath $MYDIR/lib/rhino/js.jar:$MYDIR/lib/closure/compiler.jar \
        org.mozilla.javascript.tools.shell.Main $MYDIR/build.js $MYDIR "$@"

Module Modifier registration example flawed?

The example in the API documentation (http://requirejs.org/docs/api.html#modifiers) has:

require.modify({
    "my/target1": "my/modifier1",
    "my/target1": "my/modifier2",
    "my/target2": "my/modifier3"
});

But, you cannot define the same property twice. Perhaps this was meant to be written/implemented as:

require.modify({
    "my/target1": [ "my/modifier1", "my/modifier2" ],
    "my/target2": "my/modifier3"
});

order! plugin in chrome 6

Since the release of chrome 6, the order plugin seems to be slightly broken (only in that version of the browser).

require() is sometimes (not easily reproducible) calling the "ready" function before all the code in the javascript files have been executed. Switching to recursive calls seems to fix the problem.

For example... this doesn't work...
// onready might be called before b.js is executed.
require(["order!a.js", "order!b.js"], onready);

But this does.

// haven't seen a problem doing it this way... 
require(["a.js"], function() {
    require(["b.js"], onready);
});

Relative ids are not being resolved against module URL

If I create a package where the main script points to a module that then depends on a module in the lib directory, the module ids gets resolved based on the lib directory location rather than the calling module location. For example:

require({
  packages: [
    {name:"test", main:"../main.js"} /* main should really be resolved relative to the package root, like NPM does, instead of relative to the lib directory, but that is another issue*/
  ]
});
require("test");

/main.js: (in package root)

define(["./lib/a"],...

/lib/a.js:

define(...

This will load main.js correctly, but instead of resolving "./lib/a" relative to main.js's location (resolving to /lib/a), it resolves it relative to the lib directory (I guess it's alias) and requests /lib/lib/a.js. In all other CommonJS modules, you can count on relative ids resolving against the modules location, not some alias.

use strict

Hi,

if combining require.js with other files, your "use strict" declaration works for the whole file, instead of just for requirejs.
Can you please move this statement into your closure?

Thanks.

var require, define;

As I can see you are trying to hold your code jslint valid. I think we both know about js worst part - implicit globals. Using var require, define; you are using this ugly feature and define globals using var in global scope. This is a style question, but I think you might want to follow jslint/crockford logic, so in this case you are doing it wrong.

Using window directly is also is also wrong https://github.com/douglascrockford/JSLint/issues/closed#issue/15

So the best is to use "this".

Load script without ".js" file extension

hi,

is there a way to disable RequireJS atomatically appending ".js" file extensions? coz i'm using a php minifier script to combine and compress my css and js assets, and the URL to call these compressed script doesn't always require a ".js" file extension. is there a way integrate this kind of workflow with RequireJS?

an example URL to call the combined script is like this:

http://example.com/min/g=scripts

here i'm loading an array named "scripts" (defined via config) which contains a list of js or css files. another example is to define it inline, like this:

http://example.com/min/f=scripts/jquery.js,scripts/site.js,scripts/home.js

as you see. i'm having trouble combining this with RequireJS (or even any script loader out there). i'm using Minify for compression: http://code.google.com/p/minify/

any help would be appreciated..

thx

NPM package

I can't find a npm package for requireJS. If there is one it should be more visible in the docs, if there isn't one, there should be.

`includeRequire: true` overrides source require.js from where the build tool is located

my file structure is something like this
$HOME/
requirejs/ (this is the full checkout from github - only the relevant files shown)
require.js
build/
build.sh
require/
i18n.js
text.js
src/
cps.build.js
require.js
cps/
app.js
common.js
Widget.js
require/ (this is a copy added to the src tree - only necessary files were copied)
i18n.js
text.js
build/

cps.build.js is like this:
({
appDir: './',
baseUrl: './',
dir: '../build',
optimize: 'closure',
modules: [
{
name: 'require',
includeRequire: true,
include: [
'require/i18n',
'require/text',
'cps/common'
]
},
{
name: 'cps/app',
exclude: ['cps/common']
},
{
name: 'cps/Widget',
exclude: ['cps/common']
}
]
})
from inside ~/src i then do a build:
~/requirejs/buid/build.sh cps.build.js
this causes ~/requirejs/require.js to become the require layer in my profile rather than ~/build/require.js

Incorrect dependencies handling with minified version, under IE8

  • Did not test with source ;
  • Only debugged with IE 8.0.6001.18702

The problem is with the minified version of the splitPrefix method :

g.splitPrefix=function(a,b,d){var c=a.indexOf("!"),e=null;if(c!==-1){e=a.substring(0,c);a=a.substring(c+1,a.length)}a=g.normalizeName(a,b,d);return{prefix:e,name:a,fullName:e?e+"!"+a:a}}};

When there is a dependencies definition like this :

require.def
(
'home',
[
'jquery/jquery',
'prospek/base',
'mcp/models/user',
'mcp/models/comment',
'mcp/controllers/home',
],
function ()
{
}
);

I get the following error : "'undefined' is null or not an object", which totally breaks the rest of the routine.

I understand that there should not be a trailing coma for the last element of the array. IMHO, requirejs should be modified to handle this, because it is not testing if the "a" is defined at all.

Hope this is relevant for you, and thank you for this excellent library.

FT

built layers included twice in later layers

if i have modules in my profile like this...
modules: [
{
name: 'bootstrap'
},
{
// this is the common layer for the app
name: 'app/common',
exclude: [
'bootstrap'
]
},
{
name: 'require',
includeRequire: true,
include: [
'require/i18n',
'require/text',
'bootstrap'
]
},
{
name: 'app/page1',
exclude: ['app/common']
},
{
name: 'app/page2',
exclude: ['app/common']
}
]
then the bootstrap that's included in the require layer is included twice in the build output of the require layer. it's probably the result of the bootstrap layer being built first, then including the dependencies for bootstrap in the require layer and then also including the built output of bootstrap rather than the source.

If require() throws an error, then plugin is no longer usable afterwards.

Very simple case:
From firebug console:

require("/js/main.js", function() {console.log("hello");});

Let's say /js/main.js is not on the server, and returns a 404. After 7 seconds, require throws a timeout error. Afterwards, from the Firebug console,
require("any js file", function() {console.log("hello");});

This does nothing. I am on Firefox 3.6.12. I traced it through firebug - calling require does get into the main function - none of the if statements result in true, and so it exits with "undefined". Is this expected behavior? I didn't see any documentation on how to recover from an error.

Paths ending on a slash do not work in 'paths' config option

Consider a key in a paths configuration like this:

require({
    paths : {
        "foo/" : "bar/"
    }
});

The trailing slash in foo/ seems to cause problems. The require statements using this path down the line don't use the rewritten path. Doing something like:

require({
    paths : {
        "foo/foo" : "bar/bar"/
    }
});

Does work.

I made a small test case here

a build with the order plugin outputs the module before it's dependencies

if you build requirejs/tests/order/foo.js the output is generated in the wrong order - foo.js is included before all the dependencies. it should be last.

actual:

Tracing dependencies for: foo

foo.js
----------------
require/order.js
foo.js
one.js
two.js
three.js

expected:

Tracing dependencies for: foo

foo.js
----------------
require/order.js
one.js
two.js
three.js
foo.js

Infinite recursion bug

I've been using 0.15.0 for a while now to build a project I'm working on. I just tried to upgrade to 0.22.0 today, and have run into a problem. It now gets stuck into an infinite recursion with the checkLoaded function calling it's self. It appears that context.waitCount is equal to 3, even though in the 'loaded' list, all modules are loaded. A comment suggests this could be a circular dependency issue, however it worked fine with 0.15.0, and I would expect it to point out the circular dependency if there is one.
I also tried the latest source control HEAD, and that also exhibits the problem.

recent npm package path fix only partial?

The recent fix to look for npm packaged binary addons works in some cases but not for me with express. Possible problem with dependencies?

error reported when require('express') used:

Error: RequireJS cannot find file for module: connect/middleware/router Tried pa
ths around: null (.node/index.js/index.node)
at Function.load (requirejs/requireAdapter.js:2369:19)
at Function.get (requirejs/requireAdapter.js:2288:25)
at requirejs/requireAdapter.js:937:36
at requirejs/requireAdapter.js:318:29
at Object. (/usr/local/lib/node/express/./../.npm/express/1.0.0/p
ackage/lib/express/./server.js:19:14)
at Function.execCb (requirejs/requireAdapter.js:2269:19)
at execManager (requirejs/requireAdapter.js:390:27)
at main (requirejs/requireAdapter.js:536:17)
at callDefMain (requirejs/requireAdapter.js:549:18)
at Object.completeLoad (requirejs/requireAdapter.js:1019:21)

Cache Busting

When working in a development environment where caching of scripts may be taking place, say, if some expires headers are enabled, it would be nice to allow the script tags that are injected to use and extra query like my/module.js?SOMERANDOMNOMBER, to disable any caching.

When working in a production environment where a single-file build is not possible, I usually can get the current revision of the code or some other unique identifier for the version of the app. It would be nice to be able to set something like a data-revision="MYREVISIONHASH" and have that appended to all loaded tags, or if there is a ?MYREVISIONHASH on the src attribute of the requirejs tag, have that added to all injected tags.

Don't know if this would be the best way to make sure caching behaves correctly or if there is an existing or better way to do this.

text! inlining during build doesn't work with anonymous modules

it seems that inlining text in an anonymous module fails when doing a build. ie code of this form doesn't build.

define(["text!./templates/Foo.html"], function (template) {
    // something that makes use of template...
});

the error is "Cannot resolve relative dependency: ./templates/Foo.html in file: [filename]"

NPM package

I can't find a npm package for requireJS. If there is one it should be more visible in the docs, if there isn't one, there should be.

Optimizing full project produces empty files

Thanks for the good work on RequireJS.

I have downloaded the latest version 0.14.5 and the sample project.
When I try the sample project optimizer build script by using:

..\..\requirejs\build\build.bat app.build.js

The produced result for main.js is not correct:

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

Note that I faced the same issue in my own project and after trying so many options and combinations, it still produces the same behavior:

  • Empty content (or just define statement) for any module that is part of the app.build.js
  • If the command is used specifically on one of the files individually (see documentation for optimizing single JavaScript file) the result is correct and as expected

The issue is only for optimizing whole project.

Please advise what is wrong.

IE<9

Hi!

Please, consider guarding name in req.splitPrefix by using, e.g., name = name || '';, or the subj fails to load RequireJS script

TIA,
--Vladimir

function returned by a factory is used as the factory when the module is loaded via a plugin

index.html
<script type="text/javascript">
require(["order!foo.js"], function () {
console.log('foo dependency ready');
});
</script>
foo.js
define(function () {
console.log('foo is defined');
return function () {
console.warn('foo is used!!!');
}
});

the problem is that the function returned by foo's factory gets used as the factory if foo is loaded with a plugin.

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.