How to load custom named module in RequireJS - javascript

I know it is recommended not to use them, but let's say just for fun I'd like to use module with custom name. How can I load it?
I have following structure:
-- ./index.html
-- ./js/app.js
-- ./js/test.js
In HTML, I'm loading RequireJS (2.1.14)
<script src="js/require.js" data-main="js/app" type="text/javascript"></script>
In app.js:
require(["dummy"], function(){
window.console.log("ready");
})
In test.js:
define("dummy", [], function(){
window.console.log("dummy loaded");
})
But RequireJS is trying to load dummy.js. What am I missing here?
Update:
I know I can use require.config to load the file
require.config({
paths: {
"dummy" : "test"
}
})
But then I don't understand why is one able to define custom name if he has to re-declare it again in paths...

I think you need to define this in your config (app.js) as a property of the 'paths' object:
require.config({
paths: {
dummy: 'libs/whatever'
}
});
Edit
A few notes:
In test.js, I think that you don't need to add the empty array if you don't require other modules.
In app.js, you didn't add "dummy" as function argument.
I suspect that requirejs expects you to define a return value from the module definition.
AMD = Asynchronous Module Definition
I don't think that there is a reason to use the 'define' and 'require' methods if you are not using these modules for asynchronous dependency management, rather than for executing a script.

Related

How to include anonymous functions into RequireJS dependencies?

I am starting to use RequireJS now and I was already able to add my project dependencies but I still cannot add a jQuery anonymous function yet.
For example, with my normal_file.js I do something like:
normal_file.js:
define(['dependency1'], function(Dependency) {
var Test1 = ...;
return Test1;
});
Bu from a file that has no module, like the example below, I don't know how to encapsulate it:
lib_file.js:
(function ($) {
// Do stuff...
})(window.jQuery);
the lib_file was not made by me and I'm not sure on how it really works, but I would gess it is an anonymous auto-executed function, is that so?.
Anyway, my goal is to use both files in my main code, like below:
main.js:
requirejs.config({
baseUrl:'/static/editorial/js/',
paths: {
jquery: 'third_party/jquery-1.10.2',
react: 'third_party/react-with-addons'
}
});
var dependencies = [
'third_party/react-with-addons',
'third_party/jquery-1.10.2',
'build/utils/normal_file,
'third_party/lib_file
];
require(dependencies, function(React, $, Test1, ??) {
// do my stuff
});
How should I encapsulate that anonymous function in order to add it as a dependency to my main file?
From the RequireJS docs:
Ideally the scripts you load will be modules that are defined by
calling define(). However, you may need to use some traditional/legacy
"browser globals" scripts that do not express their dependencies via
define(). For those, you can use the shim config. To properly express
their dependencies.
Read this: http://requirejs.org/docs/api.html#config-shim
It has a really good explanation of what you have to do, and gives a nice example.
Basically, you just need to set up a shim config for lib_file.js so Require knows to load the right dependencies before giving you access to that script.

Load prototype enhancements with require.js

I am using require.js to load my modules which generally works fine. Nevertheless, I do have two additonal questions:
1) If you have a module that is like a helper class and defines additional methods for existing prototypes (such as String.isNullOrEmpty), how would you include them? You want to avoid using the reference to the module.
2) What needs to be changed to use jQuery, too. I understand that jQuery needs to be required but do I also need to pass on $?
Thanks!
1) If you have a module that is like a helper class and defines
additional methods for existing prototypes (such as
String.isNullOrEmpty), how would you include them? You want to avoid
using the reference to the module.
If you need to extend prototypes then just don't return a value and use it as your last argument to require:
// helpers/string.js
define(function() {
String.prototype.isNullOrEmpty = function() {
//
}
});
// main.js
require(['moduleA', 'helpers/string'], function(moduleA) {
});
2) What needs to be changed to use jQuery, too. I understand that
jQuery needs to be required but do I also need to pass on $?
The only requirement for jQuery is that you configure the path correct
require.config({
paths: {
jquery: 'path/to/jquery'
}
});
require(['jquery', 'moduleB'], function($, moduleB) {
// Use $.whatever
});
In my opinion it's unnecessary to use the version of RequireJS that has jQuery built into it as this was primarily used when jQuery didn't support AMD.
Nowadays it does and keeping it separate allows you to swap another library out easily (think Zepto).
2/ For jquery it's really simple :
require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
$('body').alpha().beta();
});
});
More information on require site : http://requirejs.org/docs/jquery.html#get
1/ in my devs for such extension I did it in a global file without require module code.... and I include it in my app with require... not perfect, but it's work fine
global.js
myglobalvar ="";
(...other global stuff...)
myapp.js
// Filename: app.js
define([
(...)
'metrix.globals'
], function(.....){
myApp = {
(...)

Using JQuery etc. in TypeScript with RequireJS [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to require jquery via AMD in TypeScript
I created a project in TypeScript. I use RequireJS. Everything was working fine, until I need JQuery...
This is my files structure:
As you can see, I have jquery-1.8.d.ts file in the modules folder. The .js file for jQuery is inside the lib folder. When I import a module using the config file for RequireJS:
/// <reference path="../modules/require.d.ts" />
/// <reference path="AppMain.ts" />
require.config({
baseUrl: '../',
paths: {
jquery: 'lib/jquery-1.8.3'
},
shim: {
jquery: {
exports: '$'
}
},
name: "app/AppMain",
out: "../!built/Test.js",
optimize: "none"
});
require(['jquery', 'app/AppMain',
],
($, main) => {
var appMain = new main.AppMain();
appMain.run();
});
... then it's imported in JavaScript. What to do if I want it inside TypeScript? I need to use JQuery, JQueryStatic and JQueryPromise, declared inside .d.ts file.
When I try simply import a new module, I get an error:
import JQueryExternal = module("../../../modules/jquery-1.8.d"); // error: The name does not exist in the currect scope. A module cannot be aliased to a non-module type
interface Test {
MyMethod(): JQueryPromise; // here's a sample usage
}
In the beginning I thought that the path is wrong, but I tried to move it inside classes folder and next I imported it in such a way as the rest of classes. Same error:/
How to use jQuery in TypeScript in a way I want to? Is it possible?
This is completely confused:
import JQueryExternal = module("../../../modules/jquery-1.8.d");
You don't import the definition file as a module in order to use it in TypeScript. Whether you are using AMD/RequireJS or Node.js style modules to import the eventual code, you always reference d.ts definition files in the same way, at the top of your document:
/// <reference path="YOUR-RELATIVE-PATH-HERE/jquery.d.ts" />
This doesn't make the library available in JavaScript, but it will make the definitions available as you write your TypeScript.
I'm working on a large application similar in scope to yours which makes heavy use of RequireJS and JQuery. I can't see any benefit to loading JQuery as a module. I just import the reference (as described above), and make sure my page loads JQuery (and any other libraries) first:
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.9.0/jquery-ui.min.js"></script>
... etc ...
<script type="text/javascript" src="/content/client/libs/require.js" data-main="/content/client/pe.framework"></script>
I had some trouble with these two playing nicely together, so when I use requireJS with JQuery, I use a bundled version that loads them both. I don't know typescript, though, so I'm not sure how helpful this will be.
Link to the bundle: https://github.com/jrburke/require-jquery

How does AMD (require.js) handle multiple classes in a single non-amd js file?

I'm using a bunch of components from the MootoolsMore library which are all compiled into a single .js file. Is there a way to define the library once in the shim and have access to all the class with in it? The following doesn't work, but how would I do something like this?
shim:{
mootoolsMore:{
deps : ["mootools"]
exports : ["Slider", "Sortables"]
}
}
// then inside my module I could access the Slider component like so
define( function(require) {
var Slider = require('mootoolsMore').Slider
There is no need for "shim" functionality that is specific to RequireJS only. You can just use standard AMD loader API:
require(['js!path/to/MooToolsCore.js'], function(){
// nesting in order to insure that Moo Core runs first
require(['js!path/to/MooToolsMore.js'], function(){
// Your Slider and Sortables will be in global.
// just use them.
window.Slider(/* ... */)
})
})
Note, RequireJS does not need "js!" plugin to be declared explicitly, but, instead, just looks at the extension of the file. If it's ".js" it runs the file through "js" plugin. This is NON-standard behavior (as in not in AMD spec), but on RequireJS you should be able to replace line like:
['js!path/to/MooToolsMore.js']
with this:
['path/to/MooToolsMore.js']

require.js: how can I load a module that defines a name under a different name?

I'm trying to load underscore.js with require.js like this:
require(["libs/underscore-1.2.3.js"], function(_) {
...
});
But this doesn't work because underscore.js exports a module name: define('underscore', function() { ... }).
Without renaming lib/underscore-1.2.3.js, how can I load it with require.js?
Alright, after some more googling, I've found: https://github.com/documentcloud/underscore/pull/338#issuecomment-3245213
Where
#dvdotsenko all AMD loaders allow mapping a module ID to a partial path, usually the configuration is called 'paths', so to do what you want:
requirejs.config({
paths:
underscore: 'js/libs/underscore-1.2.3.min'
}
});
require(['underscore'], function () {});
Since underscore is used by other higher-level modules, like backbone, a common dependency name needs to be used to communicate a common dependency on underscore, and it makes sense to call that dependency 'underscore'. The paths config gives a way to do the mapping to a specific URL you want to use for that dependency.
This doesn't answer my question (ie, I still don't know how I'd go about loading underscore if all I had was a URL), but at least it's a functional workaround.
While this doesn't strike me as the most ideal solution, you can require your external files, and then require their registered module names in the inner block.
JSFiddle Example
require(
['require','http://documentcloud.github.com/underscore/underscore-min.js'],
function(require){
require(['underscore'],function(_){
var a = _.intersection([1,2,3],[2,3,4]);
document.write("Underscore is available in the closure : " + a);
})
}
)
It might not look pretty, but that might be a recommended pattern for loading up initial assets so that they can be required intuitively in dependent modules.

Categories