I've been refactoring my App.js file and taking some functions out into a file called utilities.js. Each function has an export and my App.js has the requisite import. However, I am getting some 'myVariable' is not defined errors for the utilities.js file. I figure this is because I am declaring the variable outside of the App() function in my App.js file, and so if you look at the utilities.js file in isolation, the variables haven't been declared. This pieceTable variable is also used in other functions in App.js.
How do you deal with this situation?
Example:
utilities.js file
export const findPieces = piece => {
pieceTable = [];
// blah blah
}
App.js file
import {findPieces} from './utilities'
let pieceTable=[];
function App() {
const findDraught = findPieces('King')
}
I get a "Failed to compile" error for this type of scenario, saying 'pieceTable' is not defined in utilities.js
If you actually want a global
When you say let pieceTable=[]; you are explicitly making pieceTable a variable with scope local to the module, i.e. not a global.
If you had just referred to pieceTable you would be assigning a property to the top-level scope object which is window (in a browser JavaScript context). You can refer to it explicitly with: window.pieceTable.
(FYI, in node.js it would be global.pieceTable. Read why.)
Globals are passé and I don't recommend using one in your case.
If you don't want a global, but you still want modular design
Choose an owning module for pieceTable and have that module export it. Then have every other module that needs to refer to pieceTable import it. This is making use of the module mechanism rather than the global mechanism.
If you want pure design
Design your functions so that they are passed in the value of pieceTable (or an object that has pieceTable as a property) as an argument to the function rather than relying on getting a singleton or global. This will make your functions easier to test as well and eliminate confusing global side effects.
My functions are not pure. I need to pass in the pieceTable as an argument when calling it, and it avoids all these issues. Don't have my utilities.js file rely on global variables in another file. Pass in arguments to these utility functions instead.
Well it's not defined in utilities.js because there's not a let or const.
If you don't want to redefine it in the utilities function, then you need to pass in the pieceTable when you call findPieces.
Related
I have declared a variable in one module like this:
// first.js
var folder;
export {folder};
and I want to use it from a different module, like this:
// second.js
import { folder} from '../js/first.js';
folder = gui.addFolder( 'Avatar Measurements' );`
TypeError: Assignment to constant variable.
Imports are read-only live bindings to the original variable in the exporting module. The "read-only" part means you can't directly modify them. The "live" part means that you can see any modifications made to them by the exporting module.
If you have a module that needs to allow other modules to modify the values of its exports (which is/should be rare), it needs to export a function that does that. For instance:
a.js:
export let folder;
export function setFolder(f) {
folder = f;
}
b.js:
import { folder, setFolder } from "./a.js";
console.log(folder); // This will be `undefined` unless another module has already modified it
setFolder(gui.addFolder("Avatar Measurements"));
console.log(folder); // This will be whatever `gui.addFolder` returns
Again, though, it is/should be very rare for a module to allow other modules to modify its exports that way.
In the comments you asked me for an example of exporting an object for this instead:
a.js:
export let shapes = {};
b.js:
import { shapes } from "./a.js";
shape.folder = gui.addFolder("Avatar Measurements");
But it's not clear to me why that object needs to live in a rather than just being local in b.
That happens because you are creating a folder constant when importing folder from ../js/first.js. You cannot reassign a value to any constant, including folder. Don't use == or ===, as those are comparasion operators and don't change the value of folder.
If you want to pass information from second.js to first.js, consider exporting a function from second.js. If you don't, then use another name for a variable, like folder_ (don't forget to declare it first: var folder_;).
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:
<script src=".../first.js"></script>
<script src=".../second.js"></script>
and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?
In order to avoid globals, you can extract the shared parts into a separate module:
shared.ts
const MY_VAR = 1337;
export { MY_VAR }
and use it in one of the other scripts:
first.ts:
import { MY_VAR } from './shared';
console.log(MY_VAR);
You need to declare this in your TypeScript file so that the compiler knows it exists.
declare var x: string; // The variable name should be the same as in your JS files.
As pointed out in a comment, you don't want to rely on implicitly declared shared variables. This can have some nasty side-effects and often is really hard to debug. However there are situations where there is no other way. You can use the globalThis object to share variables between different modules, as globalThis is everywhere the same object.
// module A
globalThis.myVar = 17;
// module B
console.log(globalThis.myVar);
You can learn more about globalThis here: MDN:globalThis
I have a function that is defined in an ES6 module (sender.js) as follows:
function send() {
// do stuff
}
export {send};
This module is then used in the application's main JavaScript file app.js as follows:
import {send} from "./sender"
The send function is available in the app.js file, however it is not in Firefox's Javascript console:
> send
ReferenceError: send is not defined
How can I import the send function in the JavaScript console?
You can set the specific function as global by assigning it to the global object –
in browsers it's window.
import {send} from "./sender";
window.send = send;
Note that while it might be useful in debugging, you shouldn't use that in production code – see Why are global variables considered bad practice?
This is b.js
var something = "hooorraaaaay!!!";
And this is a.js
require( './b.js' );
console.log(something);
Why isn't something being recognised within a.js. I understand that it has been declared with var, but my understanding is that any variable declared outside a function should act global. So why isn't this working?
Node modules are each in their own scope. By default, nothing in module a is visible to module b. Doing a require() on a module is NOT like including the source. It loads the file runs the code and then the only things that are available to the outside world are:
Any functions or properties that are explicitly exported from the module by assigning to module.exports.
Any functions or properties that are explicitly assigned to the global object in node.
So, if you want something in b.js to be exposed to the outside world, you do like this:
// b.js
module.exports.callMe = function() {
console.log("I'm in module b");
}
And, then in a.js, you can do this:
// a.js
var b = require('./b.js');
b.callMe();
This is how the module system works in node.js. It is very different than just including a <script> tag in a browser web page. You can read more about the module system in these references:
Understanding module.exports and exports in Node.js
What is the purpose of Node.js module.exports and how do you use it?
Node.js Handbook - How require() Actually Works
Internally, node.js loads a module's code and then inserts it into a wrapper function. So, each top level variable in a node module is actually only a local variable in that module function. This is why nothing is globally declared or shared by default. It is done this way on purpose so that each module comes with it's own private area for storing it's state and will not, by default, interfere with the variables of any other module.
You then explicitly export only the property/function interfaces that you want to make public and even then, they are still not exported as public symbols so again they cannot conflict with anything else.
So, the b.js code above actually gets transformed into this when node.js runs it:
(function (exports, module, require, __filename, __dirname){
module.exports.callMe = function() {
console.log("I'm in module b");
}
})(...);
The (...) contains actual variables that are passed to the module.
Let me assume you are using node.js judging from the require function.
node.js wraps each file in its own scope. this has nothing to do with the use of var keyword. every file in node.js is called a module.
Now let's say you want to include a module, here comes require, you have used it right.
But since your module doesn't export anything, it's useless when it's included in some other module.
So at the end of your b.js file, add the following line :
module.exports.something = something;
Now we can finally use our exported variable :
var b = require('./b.js');
console.log('Something is : ' + b.something);
I have been reading about this topic for several hours and just haven't found anything to help make this stick.
a module is just an object in node with a few properties, one is an exports property that references an object.
the 'exports' variable is
var exports = module.exports
It is a var pointing to the object that module.exports is referencing.
What I am struggling with is visualize what the module is. I know it's an object, but is there only one?
I know this isn't the exact way node implements a module but I am visualizing it looking something like this:
var module = {}
module.exports = {}
// now module has a property module.exports
var exports = module.exports
Now, from everything I have been reading, if you were to assign something to module.export = 'xyz'
It would hold the value 'xyz'. Does it lose the original object? On top of that, if I assigned something else to module.exports in the same file, would it be replaced with the new value?
EX:
// file = app.js
module.export = 'hello'
module.export = 'bye'
// file = newApp.js
require(./app);
what is the value of the module? Am I overriding the same module object or are there multiple?
Before we continue, it's important that you understand how modules are actually loaded by node.
The key thing to take away from node's module loading system is that before it actually runs the code you require (which happens in Module#_compile), it creates a new, empty exports object as a property of the Module. (In other words, your visualization is correct.)
Node then wraps the text in the required file with an anonymous function:
(function (exports, require, module, __filename, __dirname) {
// here goes what's in your js file
});
...and essentially evals that string. The result of evaling that string is a function (the anonymous wrapper one), and node immediately invokes the function, passing in the parameters like this:
evaledFn(module.exports, require, module, filename, dirname);
require, filename, and dirname are a reference to the require function (which actually isn't a global), and strings containing the loaded module's path information. (This is what the docs mean when they say "__filename isn't actually a global but rather local to each module.")
So we can see that inside a module, indeed exports === module.exports. But why do modules get both a module and a exports?
Backward compatibility. In the very early days of node, there was no module variable inside of modules. You simply assigned to exports. However, this meant you could never export a constructor function as the module itself.
A familiar example of a module exporting a constructor function as the module:
var express = require('express');
var app = express();
This works because Express exports a function by reassigning module.exports, overwriting the empty object that node gives you by default:
module.exports = function() { ... }
However, note that you can't just write:
exports = function { ... }
This is because JavaScript's parameter passing semantics are weird. Technically, JavaScript might be considered "pure pass-by-value," but in reality parameters are passed "reference-by-value".
This means that you when you pass an object to a function, it receives a reference to that object as a value. You can access the original object through that reference, but you cannot change the caller's perception of the reference. In other words, there's no such thing as an "out" param like you might see in C/C++/C#.
As a concrete example:
var obj = { x: 1 };
function A(o) {
o.x = 2;
}
function B(o) {
o = { x: 2 };
}
Calling A(obj); will result in obj.x == 2, because we access the original object passed in as o. However, B(obj); will do nothing; obj.x == 1. Assigning a completely new object to B's local o only changes what o points to. It does nothing to the caller's object obj, which remains unaffected.
Now it should be obvious why it was thus necessary to add the module object to node modules' local scope. In order to allow a module to completely replace the exports object, it must be available as the property an object passed in to the module anonymous function. And obviously no one wanted to break existing code, so exports was left as a reference to module.exports.
So when you're just assigning properties to your exports object, it doesn't matter whether you use exports or module.exports; they are one and the same, a reference pointing to the exact same object.
It's only when you want to export a function as the top-level export where you must use module.exports, because as we've seen, simply assigning a function to exports would have no effect outside of the module scope.
As a final note, when you are exporting a function as the module, it's a good practice to assign to both exports and module.exports. That way, both variables remain consistent and work the same as they do in a standard module.
exports = module.exports = function() { ... }
Be sure to do this near the top of your module file, so that no one accidentally assigns to an exports that ends up getting overwritten.
Also, if that looks strange to you (three =s?), I'm taking advantage of the fact that an expression containing the assignment operator returns the assigned value, which makes it possible to assign a single value to multiple variables in one shot.
You're overriding the module — exports is a single object gets pulled in with require. Typically, when doing this kind of modular JavaScript using require, your export will be a constructor rather than a primitive like a string in your example. That way, you can create new instances of functionality that's defined in the module. Example:
// module.js
var MyConstructor = function(prop) {
this.prop = prop;
});
module.exports = MyConstructor;
// app.js
var MyConstructor = require('module');
var instance = new MyConstructor('test');
console.log(instance.prop) // 'test'
Modules in Node.js are just files. Each file is a module and each module is a file. If you have more than one file, you can have more than one module (one in each file).
As per module.exports: the Node.js API documentation will shed some light on the topic:
The module.exports object is created by the Module system. Sometimes
this is not acceptable; many want their module to be an instance of
some class. To do this assign the desired export object to
module.exports. Note that assigning the desired object to exports will
simply rebind the local exports variable, which is probably not what
you want to do.
and
The exports variable that is available within a module starts as a
reference to module.exports. As with any variable, if you assign a new
value to it, it is no longer bound to the previous value. ... As a guideline,
if the relationship between exports and module.exports
seems like magic to you, ignore exports and only use module.exports.
So, what does this all mean? In your particular example, module.exports would be equal to it's last assigned value ('bye').