Feed Javascript directly into RequireJS Require function - requirejs

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"
});

Related

nodejs: how to use literals in external require?

Here is my example:
var name="Doe";
var template = require('./template.txt');
and template.txt contains:
`hello ${name}`
I got the error: name is not defined.
Any idea ?
Well you literally want to take JS code from a .txt file and run it, so you need the infamous eval
var name="Doe";
var template = require('fs').readFileSync('./template.txt');
template = template.toString().trim();
console.log(eval(template)) // will output: hello Doe
Although it can be dangerous to run JS code like this, if the templates are files that are in your control and written by you, then I guess it can be done.
Ofcourse you could simply use a template engine like EJS or nunjucks
From the Node.js documentation:
The module wrapper
Before a module's code is executed, Node.js will
wrap it with a function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) {
// Modulecode actually lives in here
});
By doing this, Node.js achieves a few
things:
It keeps top-level variables (defined with var, const or let) scoped
to the module rather than the global object.
It helps to provide some
global-looking variables that are actually specific to the module,
such as:
The module and exports objects that the implementor can use to export
values from the module.
The convenience variables __filename and
__dirname, containing the module's absolute filename and directory path.
and globals:
In browsers, the top-level scope is the global scope. This means that
within the browser var something will define a new global variable. In
Node.js this is different. The top-level scope is not the global
scope; var something inside a Node.js module will be local to that
module.
So when we define a variable in one module, the other modules in the program will not have access to that variable, but you can declare your variable without var and it will be defined as a global.
More info in this thread: Where are vars stored in Nodejs?

get path of the file the module is being called from?

Let's say I have a node.js module
module.exports = function () {
console.log(__filename);
}
And in the main file I call it like
var x = require('path/to/module');
x();
That gives me the path to the module file. For example if I stored the module at ~/project-root/lib/mod.js and the main.js file lies at ~/project-root/main.js, that setup gives me the output:
~/project-root/lib/mod.js
I want to use something in place of __filename in the module that gives me to location of of the file from which it was called from. (e.g. the output would be ~/project-root/main.js instead, in this example).
The module can be located anywhere. So using path to adjust for only this example would fail in other scenarios (for example if module is stored in ~/project-root/node_modules/ or the global node.js modules directory.
I have a feeling it's something fairly trivial and I'm overlooking something. But I haven't found a solution from anything Google has yielded during an hour long search. Maybe I'm using the wrong keywords!
Module.parent called in your module lets you access to the exports of the file it was called from.
You can put the function below in your main.js and you can call module.parent.filename() in your module.
module.exports.filename = function () {
return __filename;
}

RequireJS Dynamic Paths Replacement

I have a requirejs module which is used as a wrapper to an API that comes from a different JS file:
apiWrapper.js
define([], function () {
return {
funcA: apiFuncA,
funcB: apiFuncB
};
});
It works fine but now I have some new use cases where I need to replace the implementation, e.g. instead of apiFuncA invoke my own function. But I don't want to touch other places in my code, where I call the functions, like apiWrapper.funcA(param).
I can do something like the following:
define([], function () {
return {
funcA: function(){
if(regularUseCase){
return apiFuncA(arguments);
} else {
return (function myFuncAImplementation(params){
//my code, instead of the external API
})(arguments);
}
},
funcB: apiFuncB
};
});
But I feel like it doesn't look nice. What's a more elegant alternative? Is there a way to replace the module (apiWrapper) dynamically? Currently it's defined in my require.config paths definition. Can this path definition be changed at runtime so that I'll use a different file as a wrapper?
Well, first of all, if you use Require.js, you probably want to build it before production. As so, it is important you don't update paths dynamically at runtime or depends on runtime variables to defines path as this will prevent you from running r.js successfully.
There's a lot of tools (requirejs plugins) out there that can help you dynamically change the path to a module or conditionnaly load a dependency.
First, you could use require.replace that allow you to change parts (or all) of a module URL depending on a check you made without breaking the build.
If you're looking for polyfilling, there's requirejs feature
And there's a lot more listed here: https://github.com/jrburke/requirejs/wiki/Plugins

Returning a module in RequireJS

I'm refactoring a large javascript codebase to use RequireJS. Unfortunately, many of the files I'm dealing with are not object-oriented, and cannot return an object without significant modification. Is there a more efficient way to give 'dependent' modules access to the functions and variables contained in a module (without returning an object) ?
I have read about using the exports syntax for defining modules, but it is very unclear whether that would be a valid solution for this situation.
In a defined module, the exports object is what gets exported from the module and passed to whatever module requires it.
Consider this:
define(["exports"], function(exports){
exports.myCustomFunction = function(){};
exports.myCustomObject = {};
exports.myCustomVariable = true;
})
This module will place all the disparate functions and/or objects that you want made public onto the exports object.
At this point RequireJS will use that exports object to pass to a module that requires it:
require(["nameOfCustomModule|filename"], function(myCustomModule){
//evaluates to true
console.log(myCustomModule.myCustomVariable);
})
Here's a simple fiddle. Just bring up your console and you will see the value logged there. http://jsfiddle.net/xeucv/
Hope this clears it up a bit!

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