How to change ES6 imported array - javascript

So I have a app built using ES6 modules, I want to clear an array imported as a module in one file and add to it from another file. Pushing to the array works fine, but I can't empty the array in a delete function. Debugging wise the function is called and I get no errors but the array is not cleared.
The array clears if it is included in the same module as the clear function...
below is an example.
module_1.js
export let array = [];
//////////////////////////////////////////////////
module_2.js
import { array } from './module_1.js';
export const func = () => {array.push('hello')};
//////////////////////////////////////////////////
module_3.js
import { array } from './module_1.js';
export const clear = () => {
let array = [];
}
/////////////////////////////////////////////////
module_4.js
import { array } from './module_1.js';
import { func } from './module_2.js';
import { clear } fromt './modeule_3.js';
button.addEventListener('click', func);
button.addEventListener('click', clear);

You cannot reassign a module variable outside of the module where it was declared, even if was defined using let or var.
So, this:
//module1.js
export let foo = 'bar'
foo = 'baz'
//module2.js
import {foo} from './module1.js'
console.log(foo) //baz
...works, while this:
//module1.js
export let foo = 'bar'
//module2.js
import {foo} from './module1.js'
foo = 'baz' //TypeError
console.log(foo)
...does not.
However, mutation of objects is still allowed, that's why .push() works in your second module.
To solve the problem, you have to either:
Empty the array using mutation
You can empty an array by setting its length to zero, but this still modifies a module's data from outside, which isn't the best practice...
//module_3.js
import { array } from './module_1.js';
export const clear = () => {
array.length = 0;
}
Move all mutator methods to a single module
//module_1.js
export let array = [];
export const func = () => {
array.push('hello')
};
export const clear = () => {
array = [];
}
//module_2.js
import { func, clear } from './module_1.js';
button.addEventListener('click', func);
button.addEventListener('click', clear);
Create general-purpose functions
//module_1.js
export let array = [];
import {func as _func} from './module_2.js';
export const func = () => _func(array)
import {clear as _clear} from './module_3.js';
export const clear = () => _clear(array)
//module_2.js
export const func = (array) => {
array.push('hello')
};
//module_3.js
export const clear = (array) => {
array.length = 0;
}
//module_4.js
import { func, clear } from './module_1.js';
button.addEventListener('click', func);
button.addEventListener('click', clear);

In module_3.js you are redeclaring the array variable as let, this will define a local variable scoped to the clear function, removing let will give you the expected result.
export const clear = () => {
array = [];
};

Related

React Constants inside a Function

I need help to export the constants. I am getting different errors when i try to search for this on google or other related topics at stackoverflow.
This is my Printer.jsx
import React, { useRef, useState } from "react";
// export individual features (can export var, let,
// const, function, class)
export let ePosDev = new window.epson.ePOSDevice();
export const ePosDevice = useRef();
export const printer = useRef();
export function connectFunction() {
ePosDevice.current = ePosDev;
ePosDev.connect("192.168.1.254", 8080, (data) => {
if (data === "OK") {
ePosDev.createDevice(
"local_printer",
ePosDev.DEVICE_TYPE_PRINTER,
{ crypto: true, buffer: false },
(devobj, retcode) => {
if (retcode === "OK") {
printer.current = devobj;
} else {
throw retcode;
}
}
);
} else {
throw data;
}
}); };
I need to add the const connect to the App.js so that if the App is starting the connection is also starting. The second is that i need to add the const print to ReactB.js-file so if content of ReactB.js-page is loading the print-request should be send.
Thanks for your help! Stuck at this since 5 hours and dont know how to deal with this problems.
It seems your main issue stems around how to export constants. I recommend checking out MDN for more info: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
Below is an excerpt on named exports that is relevant to your scenario.
// export features declared earlier
export { myFunction, myVariable };
// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() { ... };
So for your example, it would just be a matter of adding declaring the const with export const connect = value; or adding export { connect }; after it is declared.

How can i use module.exports.function in es6? [duplicate]

This question already has answers here:
module.exports vs. export default in Node.js and ES6
(3 answers)
Closed 4 years ago.
I am trying to convert this code to es6 so for my react project, but I couldn't figure out(didn't get an error but couldn't achieve what I wanted to do).
here are the files.
foo.js
module.exports = () => {
console.log("hello default");
}
module.exports.bar = () => {
console.log("one functions");
}
index.js
const foo = require("./foo");
foo();
foo.bar();
I want be able to do this without using NAMED exports.
With ES6, you can make use of export and import instead of require and module.exports
export default () => {
console.log("hello default");
}
export const bar = () => {
console.log("one functions");
}
index.js
import foo, { bar} './foo';
foo();
bar();
EDIT: In order to replicate the same exact behaviour, you can leverage the fact the Javascript functions are essentially objects and you can assign more properties to them
const foo = () => {
console.log("hello default");
};
foo.bar = () => {
console.log("one functions");
};
export default foo;
Working demo
function needsAName () => {
console.log("hello default");
}
function bar () {
console.log("one functions");
}
export default {needsAName, bar}
To use it:
import functions from './Container'
functions.needsAName()
functions.bar()

How to create singleton class when I importing it from multiple places?

How can I make a Singleton class if I want to import it at multiple places?
I ended up with something like this, but I am exporting a new() instance (at least I think so) at each time I import it.
class RenderToRootAPI {
renderToRootComponent = null
setRenderComponent = ref => this.renderToRootComponent = ref
setInstance = instance => {
console.warn('setting instance')
this.renderToRootComponent.setInstance(instance)
}
deleteInstance = () => this.renderToRootComponent.deleteInstance
}
export default new RenderToRootAPI()
What you have written will export a singleton. It doesn't matter how many times you import it.
It might look a bit more clear if you write it like this as an example:
class RenderToRootAPI {
renderToRootComponent = null
setRenderComponent = ref => this.renderToRootComponent = ref
setInstance = instance => {
console.warn('setting instance')
this.renderToRootComponent.setInstance(instance)
}
deleteInstance = () => this.renderToRootComponent.deleteInstance
}
const renderToRootAPI = new RenderToRootAPI();
export default renderToRootAPI;
The class is not even exported, and the single exported instance will be used in all the modules that import it.

How can I export all functions from a file in JS?

I'm creating a unit converter, and I want to put all of the conversion functions into their own file. Using ES6 export, is there any way to export all of the functions in the file with their default names using only one line? For example:
export default all;
The functions are all just in the file, not within an object.
No, there's no wildcard export (except when you're re-exporting everything from another module, but that's not what you're asking about).
Simply put export in front of each function declaration you want exported, e.g.
export function foo() {
// ...
}
export function bar() {
// ...
}
...or of course, if you're using function expressions:
export var foo = function() {
// ...
};
export let bar = () => {
// ...
};
export const baz = value => {
// ...
};
I think there are a lot of solutions to this. And as has been answered, there's no wildcard export. But, you can 'wildcard' the import. So, I much prefer the one putting export before each of the functions you want to expose from the file:
//myfile.js
export function fn1() {...}
export function fn2() {...}
and then import it like so:
import * as MyFn from './myfile.js'
Afterwards you could use it like so:
MyFn.fn1();
MyFn.fn2();
You can also use module.exports as follows:
function myFunction(arg) {
console.debug(arg);
}
function otherFunction(arg) {
console.error(arg);
}
module.exports = {
myFunction: myFunction,
otherFunction: otherFunction,
};
Then you can import it:
import {myFunction, otherFunction} from "./Functions.js";
In my use case, I do have three reusable functions in one file.
utils/reusables.js
export const a = () => {}
export const b = () => {}
export const c = () => {}
In order to point the root folder instead of individual file names, I created a file called index.js which will comprise of all the functions that are listed in individual files.
utils/index.js
export * from './reusables'
Now, when I want to use my a function, I will have to simply import it like this
import { a } from '../utils'
Rather than calling it from its individual files
import { a } from '../utils/reusables'
You could also export them at the bottom of your script.
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
You can also aggregate submodules together in a parent module so that they are available to import from that module.
// In parentModule.js
export { myFunction, myVariable } from 'childModule1.js';
export { myClass } from 'childModule2.js';
// In top-level module
import { myFunction, myVariable, myClass } from 'parentModule.js'
For Node.js environment, what I did to export functions was this.
UserController.js
module.exports = {
signUp: () => {
return "user"
},
login: () => {
return "login"
}
}
UserRouter.js
const UserController = require('./UserController')
then login and signUp functions could be used inside UserRouter as UserController.signUp() and UserController.login()
I think there's a missing common solution, which is exporting in index.js file:
myModule/myFunctions.js
export const foo = () => { ... }
export const bar = () => { ... }
then in myModule/index.js
export * from "./myFunctions.js";
This way you can simply import and use it with:
import { foo, bar } from "myModule";
foo();
bar();
functions.js
function alpha(msj) {
console.log('In alpha: ' + msj);
}
function beta(msj) {
console.log('In beta: ' + msj);
}
module.exports = {
alpha,
beta
};
main.js
const functions = require('./functions');
functions.alpha('Hi');
functions.beta('Hello');
Run
node main.js
Output
In alpha: Hi
In beta: Hello
In case anyone still needs an answer to this in modern JavaScript:
const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }
What I like to do is to export all functions within an object:
//File.js
export default {
testFunction1: function testFunction1(){
console.log("Hello World")
},
//a little bit cleaner
testFunction2: () => {
console.log("Nothing here")
}
}
Now you can access the functions with calling the key value of the object:
//differentFile.js
import file from 'File.js'
file.testFunction1()
//Hello World
file.testFunction2()
//Nothing here

Correct way to export object in es6 module

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (https://medium.com/#rauschma/note-that-default-exporting-objects-is-usually-an-anti-pattern-if-you-want-to-export-the-cf674423ac38)
So I was wondering what's the correct way to export an object and then use it as
import utils from "./utils"
`
utils.foo()
Currently I'm doing like so
/** a.js **/
function foo(){
//...
}
export {
foo
}
/** b.js **/
import * as utils from "a";
utils.foo()
is it correct like so? Do I maintain the tree-shaking feature?
thanks
If the object you want to import/export only contains some functions (as I assume due to the Utils name), you can export the functions separately as follows:
export function doStuff1() {}
export function doStuff2() {}
And import like this:
import {doStuff1, doStuff2} from "./myModule";
However, if the object you want to export holds state in addition to methods, you should stick to a simple export default myObject. Otherwise, calling the imported methods won't work as intended, since the context of the object is lost.
As an example, the following object should be exported as a whole, since the properties of the object should stay encapsulated. Only importing and calling the increment function would not mutate myObject since the context of the object cannot be provided (since it's not imported as a whole).
const myObject = {
counter: 0,
increment: function() {
this.counter++;
}
}
export default myObject;
es6 native way to do this:
// file1.es6
export const myFunc = (param) => {
doStuff(param)
}
export const otherFunc = ({ param = {} }) => {
doSomething({ ...param })
}
// file2.es6
import { otherFunc } from './file1.es6'
import * as MyLib from './file1.es6'
MyLib.myfunc(0)
MyLib.otherFunc({ who: 'Repley' })
otherFunc({ var1: { a1: 1 } })
And so on.

Categories

Resources