I'm trying to learn RequireJS and I'm a bit confused about loading global variables. I have an external script that checks to see if window.Foo has been instantiated. Which mean I need to instantiate it before I require(//url/to/external-script) the said external script
My problem is that I'm not sure how I instantiate it in requireJS
do I define() in a separate file then load that file before I load the external script?
do I create it in the requirejs.config
Global variables are not instantiated in requirejs.config. There are basically two ways to do it.
You can use a script element and put the instantiation inline or in an external script, so long as this script element appears before the one that kicks off your module loading. So:
<script>
window.Foo = ... whatever;
</script>
The other way is to use a RequireJS module to perform the work, lets say it is called foo-config:
define(function () {
window.Foo = ... whatever;
});
And then your module that needs to have window.Foo defined must have the above module among its dependencies. This can be problematic if you are using a 3rd party module which itself uses define to define itself as an AMD module because there is no mechanism by which you can just add dependencies to such module. You can use a nested require:
require(['foo-config'], function () {
require(['third-party']);
});
but this is ugly, and error prone. If you have multiple pages on which you use third-party, you need to always remember to use a nested require to load it.
On the other hand, if that 3rd party module is not AMD-ready and consequently you use a shim configuration to load it, then you can add your module to the list of dependencies there.
shim: {
'third-party': ['foo-config'];
}
Related
I had to move some scripts to synchronious load through bundle, and I want to set those scripts as already defined, so require.js would not ask server for them in next calls.
Let me explain:
I had some scripts that were required everywhere, e.g. i18n, and jquery. So I have hundreeds if calls all around the project such as
require(['jquery', 'i18n', 'commonjs', ...
I bundled 'jquery', 'i18n', 'commonjs' into one script core.js which now is inserted in layout <script src="/core.js"></script>
All functions from jquer, i18n now can be accesses globally, without need of requiring them. I want to specifically say to reuire.js that those scripts are already loaded, something wich bundles should do.
I've read article about using bundles and tryied to put
bundle in my config file
bundles: {
'core': ['jquery', 'i18n', 'commonjs']
}
but it doesnt work, there lots of mistakes fallen and as I understood th only way to use bundle is to use r.js which optimizes js and folders.
Actually, all I want is to set some scripts as already loaded for require.js. Is ther a dirty way to do it?
There's no configuration option to mark a script as already defined. What you can do is to call define yourself with a module name and an appropriate return value. For instance, if you load jQuery with a script element before you start loading any module through RequireJS, you can do:
define("jquery", [], function () {
return $;
});
The code above makes it so that whenever any module requires the module jquery, they get the value of $. I normally place such modules like the one just before my call to require.config. It's just a convenient place for them.
Here there is a paths alias "jquery" in require.js config
Require.JS is triggering require callback for "jquery" but it doesn't trigger the require callback if absolute path is specified for jquery module.
<script type="text/javascript">
var require = {
baseUrl : "../../",
paths : {
'jquery' : '/js/jquery-1.8.3',
},
};
</script>
<script type='text/javascript' src='/js/require.js'></script>
<script type="text/javascript">
require(['jquery'],function(obj) {
console.info("jquery loaded","alias");
});
require(['jquery'],function(obj) {
console.info("jquery loaded","alias");
});
require(['/js/jquery-1.8.3.js'],function(obj) {
console.info("jquery loaded","absolute path");
});
</script>
I expected console.info from the last require statement to be executed, but it doesn't trigger. Looks like if you require a path alias and then require the absolute path,it's not triggering the callback.
Is this a bug in Require.JS or any alternate ways to get callback triggered with both path alias and absolute path?
Correct. Trying to load the same module under two different names does not work. There's good evidence this is by design.
RequireJS treats modules as singletons. (The scope of the "singelton-ness" is a RequireJS context. So the same module could be instantiated once for a context and a second time for a different context but it will never be instantiated twice for the same context.) When RequireJS loads a module, the module acquires a name. If the define call has a string as the first argument, the name is this string. Otherwise, if there was no map affecting the loading of the module, the name will be the string that appeared in require or define call that the listed the module as a dependency. So, using your configuration in the question, if you do require(['jquery'], ... or have a module foo that is defined as define(['jquery'], ... then the name that will be given to the module found at js/jquery-1.8.3 is jquery. Then there is the fact that inside a module, you get get the module name by doing something like this:
define(['module'], function (module) {
console.log("my module name: " + module.id);
});
Ok, so what happens if your module is required twice with two different module names? Remember that modules are singletons so RequireJS won't execute the define twice. Which id should the module get?
In practice, it is almost always the case that when the same module code is being loaded under two different names, it is an programming mistake rather than something the developers really wanted to do. I've never run into a codebase where RequireJS was used where it would have been valid to load jQuery both as jquery and using a path with the version number. The latter case would indeed be an error. So rather than use some sort of default behavior that will probably lead to surprises down the road, RequireJS breaks right away when you try to load the same module under two different names. This is the safe thing to do.
Now, if you really really must be able to load the same module with two names, then you can do it but you must be explicit about what you want: you can use map. This will establish an unambiguous relation between the module names you want to use. What a map does is basically saying "when code in module X requires module Y load module Z instead." So in your case:
map: {
'*':
'/js/jquery-1.8.3': 'jquery'
}
}
This says "when code in any module (*) requires /js/jquery-1.8.3 load jquery instead". In case you wonder, this won't result in a circular dependency. RequireJS will see /js/jquery-1.8.3 passed to require or define, will then inspect the map and convert it to jquery, will then find jquery in paths and convert it to /js/jquery-1.8.3 and then add the .js extension and fetch the module. After it has gone through paths it does not go back to map, because the result it gets from paths is a path, not a module name (and map only transforms module names).
Note that with the map above, there is only one module loaded, which is named jquery. If module.id were used in it, it would always have the value "jquery" and could not have any other value.
Important side note: you should not put the .js in the require call, otherwise it won't work: require(['/js/jquery-1.8.3'], ....
I'm implementing an AMD module oriented js framework that will be used on third party sites.
With this line, framework users will configure necessary modules
<script data-main="/main.js" src="/require.js"></script>
The problem is that data-main reference is loaded asynchronously so any js logic depending on modules loaded by main.js would fail unless I can be sure that it finished loading.
I'm pretty new to requirejs so not sure what's the good practices to create a framework that will be used by other people.
How could resolve this very simple problem?
EDIT
An example to explain my point
main.js
requirejs.config({
paths: {
jquery: '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min',
}
});
main js reference + extra code
<script data-main="/main.js" src="/require.js"></script>
<script>
require(['jquery'], function($) {
// since main.js is not loaded yet, it will assume that there is a jquery.js
// file on the same folder that this file
console.log('myModule was also loaded and can use jQuery');
});
</script>
If you want to depend on other libraries and are specifically targeting being in a Require pipeline, all you need to do is to declare some dependencies with
define(
'myModule', // module name
['foo'], // module dependencies
function(foo){ // module construction
var myModule = {};
.... code to set up the module ....
return myModule;
});
and Require will take care of things. This will register your module with Require and won't attempt to build your module until all of your dependencies are available. This functionality is discussed here.
Update with example
Require JS is designed to work both with and without a prebuilt configuration. The paths property of the Require config object only provides Require with information on how to attempt to find libraries which have not yet been registered. However, the registration and then dependency resolution is handled by Require regardless of how/where the module was registered. Please see this JSFiddle for a working example of how you can register and use dependencies.
Update 2 regarding config
Since RequireJS loads everything asynchronously, you are correct, your code example will not work. However, you're making an incorrect assumption about how it is "supposed" to work. You have an incorrect example of what your library's clients' Require configuration will look like. If someone else is building an application using RequireJS and they want to use your library, they should declare the path to your library in their require.config:
require.config({
paths: {
// this tells require how to load jQuery (a library maintained neither by you nor your clients).
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min',
// this tells require how to load myModule (the library you are building for your clients).
'myModule': '//example.com/js/my-module.min',
// this tells require how to load foo (a library built and hosted by your clients).
'foo': 'scripts/foo'
}
});
On the other hand, if your clients can't update their Require config to include your library in the declarations, then you're out of luck. All you can do is take all of your dependencies and bundle them up in your distribution file and then declare no dependencies:
define(
'myModule',
[], // can't declare any dependencies
function() {
// these dependencies are inside of the definition function to keep the global namespace clean
// since we need jQuery, we have to inline it:
var jQuery = ....
// same goes for d3.js
var d3 = ....
// now we can set up the module itself
var myModule = {};
.... code to set up the module ....
return myModule;
}
);
Obviously, this option means that you can't use the libraries which are being used by your clients. This means your library will be a lot heavier and include effectively duplicate code and data.
Hope that helps you understand how Require works and how other people will use your library.
I've finally used this approach
<script src="http://mydomain/js/require.js"></script>
<script>
requirejs.config({
baseUrl: 'http://mydomain/js'
});
require(['main'],function(){
// here users can do anything they want as all required libraries are loaded
});
</script>
main.js is loaded with a require instruction instead of using data-main attribute from script tag , this provides a callback where users can put their code.
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.
Let's assume this is my config.js or main.js:
require.config({
// paths are analogous to old-school <script> tags, in order to reference js scripts
paths: {
jquery: "libs/jquery-1.7.2.min",
underscore: "libs/underscore-min",
backbone: "libs/backbone-min",
jquerymobile: "libs/jquery.mobile-1.1.0.min",
jquerymobilerouter: "libs/jquery.mobile.router.min"
},
// configure dependencies and export value aliases for old-school js scripts
shim: {
jquery: ["require"],
underscore: {
deps: ["jquery"],
exports: "_"
},
backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
jquerymobilerouter: ["jquery", "backbone", "underscore"],
jquerymobile: ["jquery", "jquerymobilerouter", "backbone", "underscore"]
}
});
require(["jquery", "backbone", "underscore", "app/app.min", "jquerymobilerouter", "jquerymobile"], function ($, Backbone, _, App) {
console.log($);
console.log(Backbone);
console.log(_);
$("body").fadeIn(function () {
App.init();
});
});
If I understand correctly, the paths config option allows you to reference scripts, a-la the <script> tag within HTML. Assuming this is the case, do I still need to alias scripts like jQuery with a $ or underscore with a _ in my actual require statement below? It seems strange that I'd have to, given that if you reference jQuery with a standard <script> tag, $ can be used throughout your script automatically. Shouldn't it be the same using the paths?
I'm new to the shim config option, which I understand has replaced the deprecated order! plugin. What does the exports property actually DO? It doesn't seem to create an alias for a script; for example, if I set the exports for underscore to "whatever", and then try to console.log(whatever), it's undefined. So what's the point?
How would scripts like jQuery be properly used "globally?" That is, what's the proper way to be able to use the $ alias within my App.js module, or any other module in my "app" folder? Do I have to require jQuery within every individual module and alias $ every single time? Or is the way I've done it here the proper way?
I'd greatly appreciate any other criticisms of this particular script as well; the documentation for Require.js, in my opinion, leaves much to be desired; things I'd really like to know more about seem to get glossed over and leave me scratching my head.
Just to clear up any confusion around exports, it's assumed that any shim library attaches a property to the global context (window or root), or modifies an already-existing global property (e.g. a jQuery plugin). When requireJS gets the command to load a shimmed dependency, it examines the global context for a property matching the exports value of that shim config, and if it finds it, returns it as the value of that module. If it doesn't find it, then it loads the associated script, waits for it to execute, then finds the global symbol and returns it.
An important fact to remember is that unless the shim config contains an exports value, any init method on that config will NOT be executed. The dependency loader must locate a value for the module (which is what exports specifies) before that module can be initialized, which is why the property is required if there is a shim init for that module.
update: I also need to point out that if the module in question calls define anywhere, any shim config you have for that module will be ignored. This actually caused me some headaches because I wanted to use the shim config to call jQuery's jQuery.noConflict(true) method to un-globify jQuery and keep it scoped to just the modules that require it, but couldn't manage to get it working. (See update at bottom for info on how to easily do this using map config instead of shim config.)
update 2: A recent question on the requireJS google group made me realize that my explanation might be slightly misleading, so I'd like to clarify. RequireJS will only re-use a shimmed dependency if it was loaded via requireJS at least once. That is to say, if you simply have a <script> tag on the hosting page (say, for example, underscore), like this:
<script src='lib/underscore.js'></script>
<script src='lib/require.js' data-main='main.js'></script>
...and you have something like this in your requireJS config:
paths: {
'underscore': 'lib/underscore'
},
shim: {
'underscore': {
exports: '_'
}
}
Then the first time you do define(['underscore'], function (_) {}); or var _ = require('underscore');, RequireJS will re-load the underscore library rather than re-using the previously defined window._, because as far as requireJS knows, you never loaded underscore before. Sure, it can check to see if _ is already defined on the root scope, but it has no way of verifying that the _ that's already there is the same as the one defined in your paths config. For example, both prototype and jquery assign themselves to window.$ by default, and if requireJS assumes that 'window.$' is jQuery when it is in fact prototype, you're going to be in a bad situation.
All of that means that if you mix-and-match script loading styles like that, your page will wind up with something like this:
<script src='lib/underscore.js'></script>
<script src='lib/require.js' data-main='main.js'></script>
<script src='lib/underscore.js'></script>
Where the second underscore instance is the one loaded by requireJS.
Basically, a library has to be loaded via requireJS for requireJS to have knowledge of it. However, the next time you require underscore, requireJS will go "hey, I already loaded that, so just hand back whatever the exports value is and don't worry about loading another script."
This means you have two real options. One is what I would consider an anti-pattern: simply don't use requireJS to express dependencies for global scripts. That is, as long as a library attaches a global to the root context, you'll be able to access it, event if that dependency isn't explicitly required. You can see why this is an anti-pattern - you've basically just eliminated most of the advantages to using an AMD loader (explicit dependency listing and portability).
The other, better option is using requireJS to load everything, to the degree that the only actual script tag you should create yourself is the one that initially loads requireJS. You can use shims, but 95% of the time it's really not that difficult to add an AMD wrapper to the script instead. It might take a little more work to convert all of your non-AMD libraries to be AMD compatible, but once you've done one or two it gets a lot easier - I can take any generic jQuery plugin and convert it to an AMD module in less than a minute. It's usually just a matter of adding
define(['jquery'], function (jQuery) {
at the top, and
return jQuery;
});
at the bottom. The reason I have 'jquery' mapping to jQuery rather than $ is that I've noticed most plugins these days are wrapped in a closure like this:
(function ($) {
// plugin code here
})(jQuery);
And it's a good idea to pay attention to the intended scope. You can certainly map 'jquery' to $ directly though, assuming the plugin isn't expecting to find jQuery instead of $. That's just the basic AMD wrapper - more complex ones generally try to detect what kind of loader is being used (commonJS vs AMD vs regular ol' globals) and use a different loading method depending on the result. You can find examples of this pretty easily with a few seconds on google.
Update: The workaround I used to support using jQuery.noConflict(true) with RequireJS worked, but it required a very small modification to the jQuery source, and I have since figured out a much better way to accomplish the same thing without modifying jQuery. Luckily enough, so has James Burke, the author of RequireJS, who has added it to the RequireJS documentation: http://requirejs.org/docs/jquery.html#noconflictmap
Paths tell require.js where to look when you require that dependency.
For example i have things configured like this:
"paths": {
"jquery": "require_jquery"
},
"shim": {
"jquery-cookie" : ["jquery"],
"bootstrap-tab" : ["jquery"],
"bootstrap-modal": ["jquery"],
"bootstrap-alert": ["jquery"]
},
this means that every time in a module I do
define( ['jquery']
requirejs loads the file require_jquery from the main path instead of trying to load jquery.js. In your case it would load the jQuery source file, which would then be globally available. I personally don't like that approach and for that reason in the require_jquery.js file I do:
define( ["jquery_1.7.2"], function() {
// Raw jQuery does not return anything, so return it explicitly here.
return jQuery.noConflict( true );
} );
which means that jQuery will be defined only inside my modules. (This is because i write Wordpress plugins and so I can include my own version of jQuery without touching the outside version)
Exports (reading from the docs simply should be the name of the module you are using so that it can be detected if loading went correctly. Here is explained. So if you want to set an export for underscore it should be _
jQuery should be global as I explained, if you simply import it the file is executed and jQuery is global
EDIT - to answer the comments.
yes i mean that, you must export $ or jQuery for jQuery and _ for backbone. From what i got from the docs this is needed only in some edge cases and would not be necessary for libraries that declare themselves in the global namespace as jQuery.
I think that requirejs needs them when it has to fallback from loading jQuery from a CDN. i think that requirejs first tries to load jQuery from the CDN, then makes a check to verify that it was loaded correctly by checking that the "exported" variable exists, and if it doesn't it loads it form the local filesystem (if you had configured fallbacks, of course). This is something that it's needed when requirejs can't see a 404 coming back.
jQuery is globally available because it's declared global. If you simply load and execute the jQuery script, you will end up with two globals, $ and jQuery (or you can do as i did and avoid that). Inside the define() function you can alias jQuery to be whatever you want.
define( [ 'jquery' ], function( jq ) {
// jq is jquery inside this function. if you declared it
// globally it will be also available as $ and jQuery
} );