How to use underscore.string globally in a web page (with requireJS) - requirejs

The documentation says once underscore.string included in my application, the library is available using s, __s global variables (http://epeli.github.io/underscore.string/#others), or within underscore properties __.str or __.string.
This simple code should then work properly (with config paths correctly set) :
require(['underscore','underscore.string'], function(){
console.log(s('test').capitalize().value());
});
But it does not work at all. Here is a simple jsfiddle example. I probably did something wrong, but I can't figure out what.
https://jsfiddle.net/mvenrtgy/10/
The relevant test code is:
require.config({
paths: {
'underscore':'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min',
'underscore.string':'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min'
}
});
require(['underscore','underscore.string'], function(){
var t = 'This is a simple text I would like to SLUGIFY using unsercore.string';
// underscore is there!
console.log(typeof _)
// now check where underscore.string is...
console.log(typeof _.str);
console.log(typeof _.string);
console.log(typeof s);
console.log(typeof _s);
document.getElementsByTagName('body')[0].innerHTML = '<p>Sample text : ' + t + '</p>';
// this line will cause an error
document.getElementsByTagName('body')[0].innerHTML += '<p><em>Slugified</em> text : ' + s(t).slugify().value() + '</p>';
});

underscore.string is a well-behaved AMD library so it does not pollute the global space. You should change your require call so that it gets the parameters that correspond to the modules you are loading:
require(['underscore','underscore.string'], function(_, s){
By just making this change to your code, I get something that works. The 2nd line of your test comes up as:
Slugified text : this-is-a-simple-text-i-would-like-to-slugify-using-unsercore-string
Also, while underscore.string started as an underscore extension, it has grown beyond that, so you cannot access it through the _ global that underscore leaks into the global space, unless you take care of mixing it in with underscore. The documentation says you can do this:
_.mixin(s.exports());
But the documentation recommends against it because underscore.string will interfere with some of the basic functions that underscore exports. Use at your own risks.

Related

How to use module.exports of Nodejs [duplicate]

What is the purpose of Node.js module.exports and how do you use it?
I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.
According to the Node.js documentation:
module
A reference to the current
module. In particular module.exports
is the same as the exports object. See
src/node.js for more information.
But this doesn't really help.
What exactly does module.exports do, and what would a simple example be?
module.exports is the object that's actually returned as the result of a require call.
The exports variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:
let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
to export (or "expose") the internally scoped functions myFunc1 and myFunc2.
And in the calling code you would use:
const m = require('./mymodule');
m.myFunc1();
where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.
NB: if you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports
It's worth noting that the name added to the exports object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:
let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
followed by:
const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
This has already been answered but I wanted to add some clarification...
You can use both exports and module.exports to import code into your application like this:
var mycode = require('./path/to/mycode');
The basic use case you'll see (e.g. in ExpressJS example code) is that you set properties on the exports object in a .js file that you then import using require()
So in a simple counting example, you could have:
(counter.js):
var count = 1;
exports.increment = function() {
count++;
};
exports.getCount = function() {
return count;
};
... then in your application (web.js, or really any other .js file):
var counting = require('./counter.js');
console.log(counting.getCount()); // 1
counting.increment();
console.log(counting.getCount()); // 2
In simple terms, you can think of required files as functions that return a single object, and you can add properties (strings, numbers, arrays, functions, anything) to the object that's returned by setting them on exports.
Sometimes you'll want the object returned from a require() call to be a function you can call, rather than just an object with properties. In that case you need to also set module.exports, like this:
(sayhello.js):
module.exports = exports = function() {
console.log("Hello World!");
};
(app.js):
var sayHello = require('./sayhello.js');
sayHello(); // "Hello World!"
The difference between exports and module.exports is explained better in this answer here.
Note that the NodeJS module mechanism is based on CommonJS modules which are supported in many other implementations like RequireJS, but also SproutCore, CouchDB, Wakanda, OrientDB, ArangoDB, RingoJS, TeaJS, SilkJS, curl.js, or even Adobe Photoshop (via PSLib).
You can find the full list of known implementations here.
Unless your module use node specific features or module, I highly encourage you then using exports instead of module.exports which is not part of the CommonJS standard, and then mostly not supported by other implementations.
Another NodeJS specific feature is when you assign a reference to a new object to exports instead of just adding properties and methods to it like in the last example provided by Jed Watson in this thread. I would personally discourage this practice as this breaks the circular reference support of the CommonJS modules mechanism. It is then not supported by all implementations and Jed example should then be written this way (or a similar one) to provide a more universal module:
(sayhello.js):
exports.run = function() {
console.log("Hello World!");
}
(app.js):
var sayHello = require('./sayhello');
sayHello.run(); // "Hello World!"
Or using ES6 features
(sayhello.js):
Object.assign(exports, {
// Put all your public API here
sayhello() {
console.log("Hello World!");
}
});
(app.js):
const { sayHello } = require('./sayhello');
sayHello(); // "Hello World!"
PS: It looks like Appcelerator also implements CommonJS modules, but without the circular reference support (see: Appcelerator and CommonJS modules (caching and circular references))
Some few things you must take care if you assign a reference to a new object to exports and /or modules.exports:
1. All properties/methods previously attached to the original exports or module.exports are of course lost because the exported object will now reference another new one
This one is obvious, but if you add an exported method at the beginning of an existing module, be sure the native exported object is not referencing another object at the end
exports.method1 = function () {}; // exposed to the original exported object
exports.method2 = function () {}; // exposed to the original exported object
module.exports.method3 = function () {}; // exposed with method1 & method2
var otherAPI = {
// some properties and/or methods
}
exports = otherAPI; // replace the original API (works also with module.exports)
2. In case one of exports or module.exports reference a new value, they don't reference to the same object any more
exports = function AConstructor() {}; // override the original exported object
exports.method2 = function () {}; // exposed to the new exported object
// method added to the original exports object which not exposed any more
module.exports.method3 = function () {};
3. Tricky consequence. If you change the reference to both exports and module.exports, hard to say which API is exposed (it looks like module.exports wins)
// override the original exported object
module.exports = function AConstructor() {};
// try to override the original exported object
// but module.exports will be exposed instead
exports = function AnotherConstructor() {};
the module.exports property or the exports object allows a module to select what should be shared with the application
I have a video on module_export available here
When dividing your program code over multiple files, module.exports is used to publish variables and functions to the consumer of a module. The require() call in your source file is replaced with corresponding module.exports loaded from the module.
Remember when writing modules
Module loads are cached, only initial call evaluates JavaScript.
It's possible to use local variables and functions inside a module, not everything needs to be exported.
The module.exports object is also available as exports shorthand. But when returning a sole function, always use module.exports.
According to: "Modules Part 2 - Writing modules".
the refer link is like this:
exports = module.exports = function(){
//....
}
the properties of exports or module.exports ,such as functions or variables , will be exposed outside
there is something you must pay more attention : don't override exports .
why ?
because exports just the reference of module.exports , you can add the properties onto the exports ,but if you override the exports , the reference link will be broken .
good example :
exports.name = 'william';
exports.getName = function(){
console.log(this.name);
}
bad example :
exports = 'william';
exports = function(){
//...
}
If you just want to exposed only one function or variable , like this:
// test.js
var name = 'william';
module.exports = function(){
console.log(name);
}
// index.js
var test = require('./test');
test();
this module only exposed one function and the property of name is private for the outside .
There are some default or existing modules in node.js when you download and install node.js like http, sys etc.
Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.
Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.
Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo
Huh, so that's the reason, we do like
exports.additionTwo = function(x)
{return x+2;};
Be careful with the path
Lets say you have created an addition.js module,
exports.additionTwo = function(x){
return x + 2;
};
When you run this on your NODE.JS command prompt:
node
var run = require('addition.js');
This will error out saying
Error: Cannot find module addition.js
This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH
set NODE_PATH = path/to/your/additon.js
Now, this should run successfully without any errors!!
One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:
node
var run = require('./addition.js');
Since we are providing the path here by saying it's in the current directory ./ this should also run successfully.
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.
Suppose there is a file Hello.js which include two functions
sayHelloInEnglish = function() {
return "Hello";
};
sayHelloInSpanish = function() {
return "Hola";
};
We write a function only when utility of the code is more than one call.
Suppose we want to increase utility of the function to a different file say World.js,in this case exporting a file comes into picture which can be obtained by module.exports.
You can just export both the function by the code given below
var anyVariable={
sayHelloInEnglish = function() {
return "Hello";
};
sayHelloInSpanish = function() {
return "Hola";
};
}
module.export=anyVariable;
Now you just need to require the file name into World.js inorder to use those functions
var world= require("./hello.js");
The intent is:
Modular programming is a software design technique that emphasizes
separating the functionality of a program into independent,
interchangeable modules, such that each contains everything necessary
to execute only one aspect of the desired functionality.
Wikipedia
I imagine it becomes difficult to write a large programs without modular / reusable code. In nodejs we can create modular programs utilising module.exports defining what we expose and compose our program with require.
Try this example:
fileLog.js
function log(string) { require('fs').appendFileSync('log.txt',string); }
module.exports = log;
stdoutLog.js
function log(string) { console.log(string); }
module.exports = log;
program.js
const log = require('./stdoutLog.js')
log('hello world!');
execute
$ node program.js
hello world!
Now try swapping ./stdoutLog.js for ./fileLog.js.
What is the purpose of a module system?
It accomplishes the following things:
Keeps our files from bloating to really big sizes. Having files with e.g. 5000 lines of code in it are usually real hard to deal with during development.
Enforces separation of concerns. Having our code split up into multiple files allows us to have appropriate file names for every file. This way we can easily identify what every module does and where to find it (assuming we made a logical directory structure which is still your responsibility).
Having modules makes it easier to find certain parts of code which makes our code more maintainable.
How does it work?
NodejS uses the CommomJS module system which works in the following manner:
If a file wants to export something it has to declare it using module.export syntax
If a file wants to import something it has to declare it using require('file') syntax
Example:
test1.js
const test2 = require('./test2'); // returns the module.exports object of a file
test2.Func1(); // logs func1
test2.Func2(); // logs func2
test2.js
module.exports.Func1 = () => {console.log('func1')};
exports.Func2 = () => {console.log('func2')};
Other useful things to know:
Modules are getting cached. When you are loading the same module in 2 different files the module only has to be loaded once. The second time a require() is called on the same module the is pulled from the cache.
Modules are loaded in synchronous. This behavior is required, if it was asynchronous we couldn't access the object retrieved from require() right away.
ECMAScript modules - 2022
From Node 14.0 ECMAScript modules are no longer experimental and you can use them instead of classic Node's CommonJS modules.
ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.
You can define an ES module that exports a function:
// my-fun.mjs
function myFun(num) {
// do something
}
export { myFun };
Then, you can import the exported function from my-fun.mjs:
// app.mjs
import { myFun } from './my-fun.mjs';
myFun();
.mjs is the default extension for Node.js ECMAScript modules.
But you can configure the default modules extension to lookup when resolving modules using the package.json "type" field, or the --input-type flag in the CLI.
Recent versions of Node.js fully supports both ECMAScript and CommonJS modules. Moreover, it provides interoperability between them.
module.exports
ECMAScript and CommonJS modules have many differences but the most relevant difference - to this question - is that there are no more requires, no more exports, no more module.exports
In most cases, the ES module import can be used to load CommonJS modules.
If needed, a require function can be constructed within an ES module using module.createRequire().
ECMAScript modules releases history
Release
Changes
v15.3.0, v14.17.0, v12.22.0
Stabilized modules implementation
v14.13.0, v12.20.0
Support for detection of CommonJS named exports
v14.0.0, v13.14.0, v12.20.0
Remove experimental modules warning
v13.2.0, v12.17.0
Loading ECMAScript modules no longer requires a command-line flag
v12.0.0
Add support for ES modules using .js file extension via package.json "type" field
v8.5.0
Added initial ES modules implementation
You can find all the changelogs in Node.js repository
let test = function() {
return "Hello world"
};
exports.test = test;

Obfuscate RequireJS module name [duplicate]

This question already has an answer here:
Replace module ids with fake names
(1 answer)
Closed 7 years ago.
My project layout is:
-bin\
-out.closeure.js // (compiled from out.js using the closure compiler)
-out.js // this is the requirejs output file, no minification done)
-src\
-lib\
-library.js
-main.js
-somefile.js
Now when I use RequireJS to combine my project to a single file, is there a way to mangle the names of the module? For example in main.js instead of:
require(['somefile'], function(SomeFile){
//blah
});
I'll have
require(['a6fa7'], function(SomeFile){
//blah
});
Since I am using closure compiler to obfuscated everything, the only thing not being mangled is the module names, and I want to mangle that as well.
I looked at the https://github.com/stevensacks/grunt-requirejs-obfuscate plugin but it's not working and I'm not sure if that plugin does what I want.
Edit1: I encourage to use instead AMDclean, there may be no reason to keep the footprint amd produce on an optimized build. If you want to keep it, the following way is the workaround i made:
Use the onBuildWrite and onBuildRead as the documentation states:
onBuildWrite A function that will be called for every write to an optimized bundle of modules. This allows transforms of the content before serialization.
"replaceModuleNames": [],
//executed on every file read
onBuildRead: function(moduleName, path, contents){
this["replaceModuleNames"].push({
"name": moduleName,
"with": makeid()
});
//Always return a value.
return contents;
},
onBuildWrite: function (moduleName, path, contents) {
console.log("moduleName: " + moduleName + " ,path: " + path + " ,contents: ... ");
var text = contents;
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
this["replaceModuleNames"].forEach(function(element){
var regE = new RegExp('(?:define\\(|require\\().*(?:"|\')('+RegExp.escape(element["name"])+')(?:"|\')');
text = text.replace(regE, function(a, b){
return a.replace(b, element["with"]);
});
console.log("moduleName: "+moduleName+ " replaceWith: " + element["with"] + " result: " + text);
});
//Always return a value.
return text;
}
Place it on the build.js, you have to implement makeid method,
i tested it but it might fail, so dont rely on it for production
Edit2: text.replace(element["name"], element["with"]); may cause inconsistent code, replaced with regexp groups, i am not experienced with regex so its open to improvements.

How do you use a requirejs friendy JavaScript file without using requirejs? I.o.w. how to demodularize?

Suppose I have a JS-library, neatly wrapped in a define('myModule', function(myModule) { return myModule.someObject; });
How could I bind the myModule.someObject to global scope (please don't ask why, I know modular programming has a lot of benefits over putting stuff on the global scope), without using requirejs or any other module handling framework?
The thing is: while developing, I'd like to use requirejs. The library that we build should be able to be included by somebody using requirejs (AMD, CommonJS, whatever), but should also be available as window.SomeObject for the people that don't want to use require just for the sake of being able to use our SomeObject. After the development phase, all code will be minified and obfuscated to a single JS file.
I think I'm just googling with the wrong search terms, because all I can find is an answer to the question how to include code that isn't wrapped in a requirejs friendly define function.
Any ideas on this would greatly be appreciated. Thanks!
--- EDIT ---
My file (before it all started) looked like:
(function(define, global) {
define([a,b,c],function(theA, theB, theC) {
return theA + theB + theC; // or something, it doesn't matter
});
})(define, this);
I'm thinking of something like this:
(function(define, global) {
// same as above
})(typeof define === 'function'
? define
: function(factory /* need more args? */) { /* solution here */ }, this);
But I'm not sure how to implement it properly...
I guess you need to wrap your modules so that they could be accessed without requirejs:
if ( typeof define === "function" && define.amd ) {
define( "mymodule", [], function () {
// do your logic
return mystuff;
} );
} else {
// do your logic
window.mystuff = mystuff;
}
Look at jQuery as an example.
I would refrain from giving your module an id if you can help it, it makes it less portable. jQuery is incredibly annoying that it forces you to set a jquery path option, but they did it for compatibility reasons. Always prefer anonymous modules if you can.
From the jQuery source
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
James Burke goes into a little more detail here also.
I would instead use a more common example from the umdjs repository:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['b'], factory);
} else {
// Browser globals
root.amdWeb = factory(root.b);
}
}(this, function (b) {
//use b in some fashion.
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return {};
}));
For another example that also supports CommonJS, check out the reqwest library:
!function (name, context, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition()
else if (typeof define == 'function' && define.amd) define(definition)
else context[name] = definition()
}('reqwest', this, function () {
return {};
});
How can I provide a library to others that does not depend on RequireJS?
This allows you to ship code that does not ship with all of RequireJS, and allows you to export any kind of API that works on a plain web page without an AMD loader.
You need to make a build config file which uses wrap and almond.
It all feels pretty dirty, but I've had it working (by following the almond ReadMe) with exactly what you're describing.

Why use alternate requirejs define: define(function(require) { ... }

I have seen people use an alternate define "syntax" in require js than what is described in the require js' documentation, or in many tutorials.
The usual define "syntax":
define(['module/first'], function (firstModule) {
//Module code with a dependency on module/first goes here.
});
The alternate define "syntax":
<script data-main="app/config" src="assets/js/libs/require.js"></script>
file: config.js:
require.config({
paths: {
jquery: '../assets/js/libs/jquery'
}
});
require(['app']);
file: app.js:
define(function(require) {
var FirstModule = require('modules/first');
//Module code with a dependency on module/first goes here.
What are the advantages, and disadvantages of using this alternate "syntax"?
I think your explanation is a bit misleading: in both cases, you will have a top-level require call with a data-main attribute specifying a file to kick-start the process of requiring different modules.
So typically you will have this in your HTML:
<script data-main="app/config" src="assets/js/libs/require.js"></script>
Then, in both cases, you would have a file app/config which sets your configuration (although you could do this directly in the HTML) and more importantly calls require on your modules:
require.config({
paths: {
jquery: '../assets/js/libs/jquery'
}
});
require(['app']);
Now, it's when we get to defining modules with dependencies that these styles differ. In the amd style you pass in the module names (paths) as an array, and a function which takes the same number of arguments:
app.js
define(['module/first', 'module/second', 'module/third'], function (firstModule, secondModule, thirdModule) {
// use firstModule, secondModule, thirdModule here
});
In the simplified CommonJS syntax, you just pass require into define and then require whatever modules you need inline:
app.js
define(function(require) {
var firstModule = require('modules/first');
var secondModule = require('modules/second');
var thirdModule = require('modules/third');
// use firstModule, secondModule, thirdModule here
}
Getting back to your original question, the advantages of the CommonJS style over the amd style should be clear.
For one thing, with the conventional syntax, if there are many modules being required, it is very easy to mistakenly assign modules to the wrong variable names. Consider this common case:
define(['jquery', 'underscore', 'backbone', 'modules/first', 'modules/second', 'modules/third', 'i18n', 'someOtherModule'], function ($, _, Backbone, first, second, third, I18n, someOtherModule) {
// ...
});
Right away, you can see that when we add a new module to this list, we have to be very careful that the corresponding new function argument appears in the right place, or else we can have jQuery assigned to Backbone, etc. In some cases this can create very subtle bugs that are hard to track down.
Now consider the CommonJS syntax:
define(function(require) {
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var firstModule = require('modules/first');
var secondModule = require('modules/second');
var thirdModule = require('modules/third');
var I18n = require('i18n');
var someOtherModule = require('someOtherModule');
// ...
}
Note that:
The pairing of module to variable name is very clear.
The order of the require statements is not important, since the variable names are being paired separately rather than as a mapping between an array and a function.
The modules do not need to be assigned first. They can be assigned anywhere, so long as it is before the module is actually used.
Those are just a few reasons that come to mind, I'm sure there are others. Basically, if you just have one or two dependencies, either syntax will do fine. But if you have a complex network of module dependencies, the CommonJS syntax is probably preferable.
Note that in the RequireJS docs, they mention this small caveat:
Not all browsers give a usable Function.prototype.toString() results. As of October 2011, the PS 3 and older Opera Mobile browsers do not. Those browsers are more likely to need an optimized build of the modules for network/device limitations, so just do a build with an optimizer that knows how to convert these files to the normalized dependency array form, like the RequireJS optimizer.
But this is not a major issue:
Since the number of browsers that cannot support this toString() scanning is very small, it is safe to use this sugared forms for all your modules, particularly if you like to line up the dependency names with the variables that will hold their module values.

Using an emscripten compiled C library from node.js

After following instructions on the emscripten wiki I have managed to compile a small C library. This resulted in an a.out.js file.
I was assuming that to use functions from this library (within node.js) something like this would have worked:
var lib = require("./a.out.js");
lib.myFunction('test');
However this fails. Can anyone help or point me to some basic tutorial related to this?
Actually, all the functions are already exported. Generated JavaScript contains following lines:
var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
// …
if (ENVIRONMENT_IS_NODE) {
// …
module['exports'] = Module;
}
If you got a function called my_fun in your C code, then you'll have Module._my_fun defined.
There are some problems with this approach, though.
Optimizer may remove or rename some functions, so always specify them passing -s EXPORTED_FUNCTIONS="['_main','_fun_one','_fun_two']". Function signatures in C++ are bit mangled, so it's wise to extern "C" { … } the ones which you want to export.
Furthermore, such a direct approach requires JS to C type conversions. You may want to hide it by adding yet another API layer in file added attached with --pre-js option:
var Module = {
my_fun: function(some_arg) {
javascript to c conversion goes here;
Module._my_fun(converted_arg) // or with Module.ccall
}
}
Module object will be later enhanced by all the Emscripten-generated goodies, so don't worry that it's defined here, not modified.
Finally, you will surely want to consider Embind which is a mechanism for exposing nice JavaScript APIs provided by Emscripten. (Requires disabling newest fastcomp backend.)
The problem here is that your a.out.js file is going to look like this
function myFunction() {
...
}
Not like this
function myFunction() {
...
}
exports.myFunction = myFunction;
You need to write a build script that lists the tokens you want to publically export from each C program and appends exports.<token> = <token>;\n to the end of your file for each token.

Resources