I'm working on a page that is in progress of transitioning from script tags to require.js. This means that some dependencies are loaded via <script> and others via require.
For the most part, in my require modules I can still treat global scripts as modoules (and thereby help the transition) by doing something like this in my bootstrapping file
define('Globalize', Globalize);
define('knockout', ko);
However this won't work with jQuery since it is a function and require will try to invoke it as a callback. Is there a way to tell require "yes this is a function but return it directly, don't try to invoke it"?
And yeah, I can't just load jquery twice because I've got bootstrap modifying it, and things depending on bootstrap
Oh...
define('jquery', function() { return window.jQuery});
duh.
Related
I'm getting this error when I browse my webapp for the first time (usually in a browser with disabled cache).
Error: Mismatched anonymous define() module: function (require) {
HTML:
<html>
.
.
.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script> var require = { urlArgs: "v=0.4.1.32" }; </script>
<script data-main="assets/js/main" src="assets/js/libs/require.js"></script>
<script src="assets/js/ace/ace.js?v=0.4.1.32"></script>
</body>
</html>
JS:
$(function () {
define(function (require) {
// do something
});
});
Anyone know exactly what this error means and why its happening?
source file, a short discussion about it in the github issues page
Like AlienWebguy said, per the docs, require.js can blow up if
You have an anonymous define ("modules that call define() with no string ID") in its own script tag (I assume actually they mean anywhere in global scope)
You have modules that have conflicting names
You use loader plugins or anonymous modules but don't use require.js's optimizer to bundle them
I had this problem while including bundles built with browserify alongside require.js modules. The solution was to either:
A. load the non-require.js standalone bundles in script tags before require.js is loaded, or
B. load them using require.js (instead of a script tag)
In getting started with require.js I ran into the issue and as a beginner the docs may as well been written in greek.
The issue I ran into was that most of the beginner examples use "anonymous defines" when you should be using a "string id".
anonymous defines
define(function() {
return { helloWorld: function() { console.log('hello world!') } };
})
define(function() {
return { helloWorld2: function() { console.log('hello world again!') } };
})
define with string id
define('moduleOne',function() {
return { helloWorld: function() { console.log('hello world!') } };
})
define('moduleTwo', function() {
return { helloWorld2: function() { console.log('hello world again!') } };
})
When you use define with a string id then you will avoid this error when you try to use the modules like so:
require([ "moduleOne", "moduleTwo" ], function(moduleOne, moduleTwo) {
moduleOne.helloWorld();
moduleTwo.helloWorld2();
});
I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.
To get rid of the error, include all your other js files by using requirejs.
Per the docs:
If you manually code a script tag in HTML to load a script with an
anonymous define() call, this error can occur.
Also seen if you
manually code a script tag in HTML to load a script that has a few
named modules, but then try to load an anonymous module that ends up
having the same name as one of the named modules in the script loaded
by the manually coded script tag.
Finally, if you use the loader
plugins or anonymous modules (modules that call define() with no
string ID) but do not use the RequireJS optimizer to combine files
together, this error can occur. The optimizer knows how to name
anonymous modules correctly so that they can be combined with other
modules in an optimized file.
To avoid the error:
Be sure to load all scripts that call define() via the RequireJS API.
Do not manually code script tags in HTML to load scripts that have
define() calls in them.
If you manually code an HTML script tag, be
sure it only includes named modules, and that an anonymous module that
will have the same name as one of the modules in that file is not
loaded.
If the problem is the use of loader plugins or anonymous
modules but the RequireJS optimizer is not used for file bundling, use
the RequireJS optimizer.
The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:
<script>
window.__define = window.define;
window.__require = window.require;
window.define = undefined;
window.require = undefined;
</script>
<script src="your-script-file.js"></script>
<script>
window.define = window.__define;
window.require = window.__require;
window.__define = undefined;
window.__require = undefined;
</script>
Not the neatest but seems to work and has saved a lot of refractoring.
Be aware that some browser extensions can add code to the pages.
In my case I had an "Emmet in all textareas" plugin that messed up with my requireJs.
Make sure that no extra code is beign added to your document by inspecting it in the browser.
Or you can use this approach.
Add require.js in your code base
then load your script through that code
<script data-main="js/app.js" src="js/require.js"></script>
What it will do it will load your script after loading require.js.
I was also seeing the same error on browser console for a project based out of require.js. As stated under MISMATCHED ANONYMOUS DEFINE() MODULES at https://requirejs.org/docs/errors.html, this error has multiple causes, the interesting one in my case being: If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer. As it turns out, Google Closure compiler was getting used to merge/minify the Javascript code during build. Solution was to remove the Google closure compiler, and instead use require.js's optimizer (r.js) to merge the js files.
I'm trying to just load the event_broker module in the chaplinjs . I am able to to do by doing something like
require(["underscore", "chaplin"], function(_, chaplin)
{
var eventBroker = _({}).extend(chaplin.EventBroker);
});
But, this is not good enough in my case. I need to be able to load the event_broker module synchronously. I know that is what require designed to do. Is there a way to do that?
I know that is what require designed to do.
No, that's not what RequireJS is designed to do. (Did you forget to put "not" in there?) RequireJS is designed to load modules asynchronously.
I would normally suggest loading Chaplin through a script element because that would be synchronous but, after looking at the code of Chaplin, I see that it fails with throw new Error('Chaplin requires Common.js or AMD modules'); if it does not detect a CommonJS or AMD environment.
Almond can be used to load bundles of AMD modules synchronously so this may be an option for you.
I'm trying to use Almond.js and the Require.js optimizer to make a standalone file that can be used without Require.js. I've been able to successfully compile the file, and all the code runs, but there's one problem: the code executes in the wrong order.
Let's say my main file (the one that's in the include= option passed to the optimizer) has the following:
console.log('outside');
require(['someFile'], function(someModule) {
console.log('inside');
window.foo = someModule.rightValue;
});
and then out in my HTML I have:
<script src="myCompiledFile.js"></script>
<script>
console.log('out in the HTML');
</script>
Since I'm using almond.js and a compiled file (and therefore there's no file loading going on) I would expect to get the output:
outside
inside
out in the HTML
However, it turns out there's still some asynchronicity going on, because what I actually see is:
outside
out in the HTML
inside
and if I try to check window.foo from the HTML it's not there.
So, my question is, how can I get the code to be more like a normal/synchronous JS file, which runs all its code first before passing things on to the next script block? I can't exactly tell my users "wrap all your code in a window.setTimeout".
By default Almond replicates the timing semantics of RequireJS' require call. Since require is asynchronous in RequireJS, it is also asynchronous in Almond. This can be readily observed in the source: Almond uses a setTimeout to schedule the execution of a module even though it could execute it right away. It makes sense because in the general case developers don't expect that the code they've crafted to work asynchronously will suddenly become synchronous just because they are using Almond. It does not matter in every project but in a project where the UI (for instance) should be refreshed in a certain order, changing the timing semantics could break the code.
Two options:
As the comment just before the setTimeout states, using require('id') works globally with Almond. This is because once your bundle is loaded, everything is guaranteed to have been loaded (since Almond does not load dynamically).
There's also a way to call require with extra arguments. If the fourth argument is true, the call is going to be synchronous:
require(['someFile'], function(someModule) {
console.log('inside');
window.foo = someModule.rightValue;
}, undefined, true);
This can be ascertained by reading the code of Almond. There's no documentation I could find on forceSync (that's the name of the parameter in question) but some bug reports mention it and I've not seen any comment there that it is meant to be a private functionality.
Good evening,
im new with requireJs and hope my questions are not stupid, its my first :).
Why the guy is using in the code above require and requirejs, whats the difference?
require(["config"], function(config){
requirejs.config(config);
require(["App", "ember"], function(App, Ember){
var app_name = config.app_name || "App";
root[app_name] = App = Ember.Application.create(App);
App.deferUntilDOMReady();
});
});
Is there a differences beetween the different code spellings?
Will the script ressources are loaded asynchon or synchron in both cases?
If i use requirejs-jquery are jquery (the $) than global or only local scope (amd scope)?
require(['script1','script2'], function() {}
require(function(require) {
require('script1');
require('script2');
}
Is it possible to have several require configs?
For example i have a bunch of nested structures like /modules/helper/example/js/example.
At the moment i have all required shims,paths inside the main.js config.
I want to place a main.js or config.js inside each helper module, which configer the required shims, pathes, etc.
Than i no longer need places all configs, pathes inside the main.
1.1
RequireJS registers TWO instances of itself in global scope - require and requirejs - really just for one reason - if one (most likely require) is overriden with another require that is different in scope or implementation, you still have requirejs - usually always a global. This separation is important when you plan to consume resources that are relative to the module you are in now.
// contents of 'a/b/c.js' module file
define(['require'], function(require){
// "local scope" require call
// resolves to 'a/b/d.js' file
require(['./d'], function(d){})
// "global scope" require call
// resolves to 'd.js' file
requirejs(['./d'], function(d){})
})
Note that asking for local require only makes sense in define calls. As define call is what establishes the "module" and it's ID. The above is equivalent to this named define:
// contents of whatever file
define('a/b/c', ['require'], function(require){
// "local scope" require call
// resolves to 'a/b/d.js' file
require(['./d'], function(d){})
// "global scope" require call
// resolves to 'd.js' file
requirejs(['./d'], function(d){})
})
The other, secret, reason why James put requirejs in there is to force you to keep using require in local scope because his build tool looks for that specific string require to find the require calls. You do this, and r.js suddenly cannot follow you dependency tree because myLocalRequire is not what r.js expects:
// contents of 'a/b/c.js' module file
define(['require'], function(myLocalRequire){
// "local scope" require call
// resolves to 'a/b/d.js' file
myLocalRequire(['./d'], function(d){})
// "global scope" require call
// resolves to 'd.js' file
require(['./d'], function(d){})
})
1.2 RequireJS does NOT do sync loading at all. The only place where you think that "it must be sync!" - the CommonJS style call like var a = require('a') it's still not. It yanks the resource out of cache. In other words, it never loads anything sync.
1.3 Don't use bundled RequireJS+jQuery. It makes an already huge jQuery more huge and interferes with browser cache. (Instead of using cached jQuery from CDN you force user to download same jQuery again - 100k of trash).
See this instead: Use jQuery as a dependency without loading jQuery with RequireJS?
2.0 Don't. separate configs is a trap. It's hell that you willingly enter once you start "building" your apps. I dare you to give me one example of a separate sane config that I cannot express as either named defines group or "packages" where main module loads relative resource.
The only thing that must be in your RequireJS config is 'baseUrl' and 2-5 globally-used 'paths' definitions. That's it.
I have a little Greasemonkey script that communicates with a servlet on (my) server. The servlet is sending back JavaScript code, which I eval() in the onload handler of the GM_xmlhttpRequest.
So far, all is working fine. Now, I'd like to use send another GM_xmlhttpRequest from within that eval()ed code. and here I'm stuck. I do not see any error, but all GM_* functions appear not to be working from within the eval(responsetext).
If I hard code the GM_xmlhttpRequest in the onload handler (no eval()), it is working fine.
It is possible to work around this problem, you can call GM_* functions with setTimeout set to 0 from eval'ed code. Try something like:
function myFunction()
{
GMXmlHttpRequest(...)
}
eval('setTimeout(myFunction, 0)');
A better solution is to extend Function.prototype with a function called safeCall that does this for you. Whenever you have any eval'ed code that will call into GM_* functions you'll need to have safeCall somewhere in that call chain.
Greasemonkey (GM) is hosting the user script, which means that it can add functions and objects to the user script, when you call eval() the script runs unhosted (the vanilla JavaScript is running it) and you don't get the GM API inside of it.
There is another solution. I have the similar problem, I don't want to put all my logic in user script, because if I change them, user need to update them by themselves. So what I want to do is separating the main logic from loading logic, the main logic will be loaded at beginning by the user script and eval them.
So I made a function "sendRequest", which is a wrapper of GM_xmlhttpRequest(), I need it anyway, because the method, server url and onError callback are always same for my application, so I just put them into my "sendRequest" function to make the xmlhttprequest simple.
In the main logic javascript code, which is loaded from server, there is no greasemonkey function call at all. If I want to for example communicate with server, I will call sendRequest instead. It works.