How to access an AMD module ("define") from ordinary JavaScript? - javascript

I made a TypeScript code which was compiled like this:
define("Global/Global", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Global = (function () {
function Global() {
}
Global.transition_time = 200;
return Global;
}());
exports.Global = Global;
});
Now, in a classic "script.js" I'm trying to console.log() the "transition_time" value. But it tells me "Global is not defined".
I put a breakpoint in the console in the Global's function, but it's never triggered.
EDIT :
That's the Global's TypeScript code:
export class Global {
static transition_time: number = 200;
}

It looks like you have an AMD module there, so you'll need to use an AMD module loader such as RequireJS if you aren't using one already. Then the proper syntax to access your module from script.js is like this:
require(["Global/Global"], function(Global_module) {
console.log(Global_module.Global.transition_time);
});
The require function doesn't add anything to the global namespace; instead, you have to pass a callback that receives the module you asked for and does whatever you wanted with it. Note the Global_module.Global.transition_time; Global_module is the name I gave to the variable that receives the entire module, and Global is the name of the exported class within the module.

Related

Re: How can I import a javascript AMD module into an external TypeScript module? (When using module.exports=...)

Related question:
How can I import a javascript AMD module into an external TypeScript module?
I have tried the workaround in the question above, it surely works. But it did not work when the AMD module returns function itself as the module (not {message:Function}, but Function itself) using module.exports=function ..
log.js: (same as the question above)
define(["require", "exports"], function(require, exports) {
function message(s) {
console.log(s);
}
exports.message = message;
});
log.d.ts:(same)
declare module 'log'{
export function message(s:string);
}
log2.js:
define(["require", "exports","module"],function(require, exports,module) {
function message(s) {
console.log(s);
}
module.exports = message;
});
log2.d.ts:
declare module 'log2'{
export default function (s:string);
}
main.ts:
import log = require('log');
log.message("hello"); // It works
import log2 = require('log2');
log2("hello"); // Error error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof import("log2")' has no compatible call signatures.
log2.default("hello"); // Compile passed. But runtime error on the browser (Uncaught TypeError: log2.default is not a function)
I compiled these *.ts files with tsc -m amd(tsc Version 3.2.4), and used require.js 2.3.5 to run the program on the browser. But log2 does not run( See main.ts ).
Maybe I am misunderstanding the use of export default in log2.d.ts . How can I write the type definition correctly?
Try this:
// log2.d.ts
declare module 'log2'{
function message(s: string);
export = message;
}
See also: the Handbook.

JavaScript TypeError: contract is not a function [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;

Javascript, multi file modules and Require.Js

I am designing a not-trivial application in Javascript.
From what i read so far a common practice is to avoid cluttering the global namespace by defining everything into modules.
And for convenience and code clarity a module can be divided into separate files using the module Augmentation pattern
var MODULE = (function (my) {
// functions, objects, etc ...
return my;
}(MODULE || {}));
Now when having many modules and module dependencies, require.Js seems like a promising tool to add order, decoupling and cleaner namespace. having all modules loaded asynchronously and make sure they run only after their dependencies are ready.
define(["depenencyModule1", "depenencyModule2"],
function(depenencyModule1, depenencyModule2) {
// define MyModule
return MyModule;
}
);
This usage however interferes with the module augmentation pattern from before, at first it seems like i am using it wrong but then i went through require.js documentation and found this:
"Only one module should be defined per JavaScript file, given the nature of the module name-to-file-path lookup algorithm."
So now i am confused, If i write my module to a single file it will be huge and maintainable, doesn't that make require.js useless?
Or perhaps Javascript concept of a module is a tiny bit of code compare to modules in other languages ?
RequireJS allows you to have a facade module which is implemented as a group of RequireJS modules. For instance, you could have:
define(function (require, exports, module) {
'use strict';
var foo = require("./foo");
var bar = require("./bar");
for(var prop in foo) {
exports[prop] = foo[prop];
}
for(var prop in bar) {
exports[prop] = bar[prop];
}
});
This module exports everything from foo and bar. From the point of view of someone importing it, it looks like a single module, even though three RequireJS modules are involved (the facade, and the two modules it imports).
Another thing I've done is declare a single class across multiple modules. I might have a foo module that exports the class Foo:
define(function (require, exports, module) {
'use strict';
var core = require("./foo_core");
require("./foo_init");
require("./foo_gui");
...
exports.Foo = core.Foo;
});
The foo_core module actually defines the class:
define(function (require, exports, module) {
'use strict';
function Foo () {
// ...
}
Foo.prototype.bar = function () { ... };
exports.Foo = Foo
});
Other modules add to it. foo_init:
define(function (require, exports, module) {
'use strict';
var Foo = require("./foo_core").Foo;
Foo.prototype.init = function () { ... };
});
foo_gui:
define(function (require, exports, module) {
'use strict';
var Foo = require("./foo_core").Foo;
Foo.prototype.render = function () { ... };
Foo.prototype.erase = function () { ... };
});
I've used both methods above to split code which from the standpoint of the API should appear as a single module but is implemented across multiple files.

Require and extend classes in Electron, how to?

I have a file global.js that contains
var Global = (function () {
function Global() {
this.greeting = 'test';
}
Global.prototype.getList = function () {
return "Hello, " + this.greeting;
};
return Global;
})();
and another file 'main.js', that contains
var global= new Global();
console.log(global.getList);
then i require them in the index.html
...
<script>
require('./npmMain.js');
require('./main.js');
</script>
and i get Global is not defined
How can i make the class available to main.js?
Any ideas?
edit: if i console.log('test'); inside npmMain.js i can see it run, so the file is getting required, just that class is not available or something
Welcome to the world of modules!
First, inside of your main.js file, add a line at the top like this:
var Global = require('./npmMain.js').Global;
Then at the end of npmMain.js add a line like this:
exports.Global = Global;
Then remove that line from index.html. That should do it.
I am guessing that you are not familiar with CommonJS style modules. Modules do not share global variables. Everything (except for a few properties supplied by the commonJS implementation) needs to be required before it can be used. Also, if you want to expose values between modules, you need to use exports keyword.
There is a much more detailed explanation on the CommonJS site.

Export a constructor from a CommonJS style module in RequireJS

I am attempting to export a constructor function using the exports object in a CommonJS style module. For some reason, requiring the module results in an empty object being returned instead of the exported function.
For example, this module;
define(function(require, exports) {
var Example = function() {
this.example = true;
};
exports = Example;
});
Results in a Uncaught TypeError: object is not a function error when it is required in another module and instantiated.
define(function(require, exports) {
var Example = require('example');
var example = new Example();
});
However, if I modify the module to return the constructor instead of using the exports object everything works as expected.
define(function(require, exports) {
var Example = function() {
this.example = true;
};
return Example;
});
Is there anyway around this?
Just like you would do in Node.js, you have to assign to module.exports rather than exports itself. So:
define(function(require, exports, module) {
var Example = function() {
this.example = true;
};
module.exports = Example;
});
Assigning to exports cannot work because exports is a variable that is local to your function. There is no way for anything outside of the function to know that you've assigned to it. When you assign to module.exports. It is a different matter because you are modifying the object to which module refers.
The RequireJS documentation suggests doing it like you did in your last snippet: just return the value you'd assign to module.exports.

Categories

Resources