Load a module if it exists - requirejs

I tested the code below, but it does not work. I just tested whether the module is loaded.
var Url=window.location.href;
var decomposedulr=Url.split("/");
console.log(decomposedulr);
var Getter=decomposedulr[decomposedulr.length-1];
//The problem is defined test if module is loaded, not if module exist
if(require.defined("Module/"+Getter[0]+"/"+Getter[1]+"/"+Getter[1]")){
requirejs(["Module/"+Getter[0]+"/"+Getter[1]+"/"+Getter[1]],function (Module) {
Module.Main();
});
}
How can I load a module only if it exists ?

"Does a module exist?" is an ambiguous question. You've discovered that require.define check whether a module is loaded, but what you want is to check whether calling require with some module name will actually load a module or not. RequireJS provides no way to perform this check before loading a module.
What you can do is just try to load the module and provide an errback to record the fact that the module is not available:
require(["someModule"], function (someModule) {
// If we get here the module exists. Use it.
},
function (err) {
// This is the errback. We get here if the module could not be loaded.
// Perform whatever alternative is needed.
});

Related

Feed Javascript directly into RequireJS Require function

We have require implemented in our web app and is working a treat. The change up now is that we have some javascript that is dynamically created at runtime on the client. Is there a way with require to directly inject a string of javascript directly into the require() function.
Currently we have:
require([moduleToLoad], function(mod){ //DO SOMETHING}});
Want something like (forgive the syntax because just writing it out):
var jsString = "define(['Text!something.htm'], function (control_Template) { //MODULE LOADED JAVASCRIPT}))";
require(jsString, function(mod){ //DO SOMETHING}});
Does anyone know how and if we can accomplish this?
Thanks
You can use named modules syntax in your string for defining the AMD module. Eval this string and then require the module using the name you have provided.
Define module like following
eval("define('runtimemodule', ['Text!something.htm'], function(){ return 'template here' })")
Require module like following
require(["runtimemodule"], function(mod){
console.log(mod); //logs "tempalte here"
});

Check if the required module is a built-in module

I need to check if the module that is going to be loaded is a built-in or an external module. For example, suppose that you have a module named fs inside the node_modules directory. If you do require("fs") the built-in module will be loaded instead of the module inside node_modules, so I'm sure that this question has a solution.
Example:
var loadModule = function (moduleName){
if (isCoreModule (moduleName)){
...
}else{
...
}
};
loadModule ("fs");
process.binding('natives'); returns an object that provides access to all built-in modules, so getting the keys of this object will get you the module names. So you could simply do something like:
var nativeModules = Object.keys(process.binding('natives'));
function loadModule(name) {
if (~nativeModules.indexOf(name)) {
// `name` is a native module name
} else {
// ...
}
};
loadModule('fs');
you can use require.resolve.paths(str):
1- if str is core module the call will return null.
2- if str is not core module you will get an array of strings.
My first attempt would be: require.resolve(moduleName).indexOf('/') <= 0. If that is true, it's a core module. Might not be portable to windows as implemented, but you should be able to use this idea to get going in the right direction.
Aside: beware require.resolve does synchronous filesystem IO. Be careful about using it within a network server.
Aside: Careful with the term "native" which generally means a native-code compiled add-on, or a C/C++ implementation. Both "core" and community modules can be either pure JS or native.
I think "core" is the most accurate term for built-in modules.
Aside: best not to shadow global variable names, so moduleName instead of just module which can be confusing with the global of the same name.
Module.isBuiltin Added in: v18.6.0, v16.17.0
import { isBuiltin } from 'node:module';
isBuiltin('node:fs'); // true
isBuiltin('fs'); // true
isBuiltin('fs/promises'); // true
isBuiltin('wss'); // false

RequireJS - loading multiple config files

I am trying to load several RequireJS configs. In my html I am loading my main config via
<script src="../lib/require.js" data-main="../app/requireConfig"></script>
and once the document is ready I want to load all my plugin configs. So I created a new define file which holds a function that calls require.config:
define(['sharedServices/logger'], function (logger) {
function configVideo() {
logger.info('Adding video modules');
require.config({
path: {
Capabilities: 'videoProvider/Capabilities',
VideoProviderEnums: 'videoProvider/VideoProviderEnums',
VideoProviderCommon: 'videoProvider/VideoProviderCommon',
VideoProviderInstance: 'videoProvider/VideoProviderInstance',
DummyVideoInstance: 'videoProvider/DummyProvider/DummyVideoInstance'
}
});
}
return {
configVideo: configVideo
};
})
However, I get the following error:
Uncaught Error: Mismatched anonymous define() module: function (logger) {
The error you're getting isn't directly related to the stated problem (loading multiple configurations), but is caused by the way your code loading is organized. As the manual says:
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.
So the problem now is that when loading the module manually (as you state "when the document is ready", could you clarify how the quoted source is actually loaded?) requirejs doesn't know where the module came from, so it can't assign it a name. If the module were loaded via requirejs api (e.g. if it appeared in a dependencies list of a define call) and it were requirejs itself that determined its script path, it would name the module after the file.
In general it is advisable to have just a single script tag loading all the requirejs-managed javascript. This makes the development setup more closely match the eventual optimized situation (where all the scripts are concatenated together). It is still possible to make require.config calls inside individual modules if necessary and make some code execute only after document is ready. As an example, many our apps do something like the following in their main.js (the module loaded by the requirejs script tag):
// sort of bootstrap config
require.config({
packages: [{
name: "our-framework",
location: "../../our-framework/src/"
}],
// here some app-specific requirejs options
waitSeconds: 5
});
// load the framework, the "our-framework/rjs-config" contains
// framework specific requirejs config (another require.config call)
require(["our-framework/rjs-config"], function() {
// in this context both require configs are loaded
require(["application"], function(application) {
application.init().run();
});
});

What is the use of module.parent in node.js? How can I refer to the require()ing module?

I was looking in the node.js module documentation, and noticed that each module has a property- module.parent. I tried to use it, but got burnt by the module caching- module.parent only ever seems to the module that first require()'d it, irrespective of current context.
So what is the usage of it? Is there any other way for me to get a reference to the current require()ing module? Right now I'm wrapping the module in a function, so that it is called like:
require("mylibrary")(module)
but that seems sub-optimal.
The "parent" is the module that caused the script to be interpreted (and cached), if any:
// $ node foo.js
console.log(module.parent); // `null`
// require('./foo')
console.log(module.parent); // `{ ... }`
What you're expecting is the "caller," which Node doesn't retain for you. For that, you'll need the exported function you're currently using to be a closure for the value.
There is a workaround for this. Node adds a module to the module cache before it finishes loading it. This means that a module can delete itself from the module cache while it's loading! Then every time the module is require'd a new instance of the module is loaded.
Magic.js
console.log('Required by ' + module.parent.filename);
delete require.cache[__filename];
Module1.js
//prints "Required by Module1.js"
require('./Magic');
Module2.js
//prints "Required by Module2.js"
require('./Magic');
Of course the side-effect of this is that your module is no longer a singleton, so you have to code Magic.js with that in mind. If you need to store global data you can always keep it in a require()'ed module that doesn't delete itself from the cache.
Update for 2022
Note the technique described above doesn't work for ES Modules included with import. As far as I know there is no good way to detect the importing ES Module.

When should I use require() and when to use define()?

I have being playing around with requirejs for the last few days. I am trying to understand the differences between define and require.
Define seems to allow for module separation and allow for dependency ordering to be adhere. But it downloads all the files it needs to begin with. Whilst require only loads what you need when you need it.
Can these two be used together and for what purposes should each of them be used?
With define you register a module in require.js that you can then depend on in other module definitions or require statements.
With require you "just" load/use a module or javascript file that can be loaded by require.js.
For examples have a look at the documentation
My rule of thumb:
Define: If you want to declare a module other parts of your application will depend on.
Require: If you just want to load and use stuff.
From the require.js source code (line 1902):
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
The define() function accepts two optional parameters (a string that represent a module ID and an array of required modules) and one required parameter (a factory method).
The return of the factory method MUST return the implementation for your module (in the same way that the Module Pattern does).
The require() function doesn't have to return the implementation of a new module.
Using define() you are asking something like "run the function that I am passing as a parameter and assign whatever returns to the ID that I am passing but, before, check that these dependencies are loaded".
Using require() you are saying something like "the function that I pass has the following dependencies, check that these dependencies are loaded before running it".
The require() function is where you use your defined modules, in order to be sure that the modules are defined, but you are not defining new modules there.
General rules:
You use define when you want to define a module that will be reused
You use require to simply load a dependency
//sample1.js file : module definition
define(function() {
var sample1 = {};
//do your stuff
return sample1;
});
//sample2.js file : module definition and also has a dependency on jQuery and sample1.js
define(['jquery', 'sample1'], function($,sample1) {
var sample2 = {
getSample1:sample1.getSomeData();
};
var selectSomeElement = $('#someElementId');
//do your stuff....
return sample2;
});
//calling in any file (mainly in entry file)
require(['sample2'], function(sample2) {
// sample1 will be loaded also
});
Hope this helps you.
"define" method for facilitating module definition
and
"require" method for handling dependency loading
define is used to define named or unnamed modules based on the proposal using the following signature:
define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the module or object*/
);
require on the other hand is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies
Refer to https://addyosmani.com/writing-modular-js/ for more information.
require() and define() both used to load dependencies.There is a major difference between these two method.
Its very Simple Guys
Require() : Method is used to run immediate functionalities.
define() : Method is used to define modules for use in multiple locations(reuse).

Resources