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

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()

Related

how to mock an imported class in my script from a jest test

in one of my constructors, i instantiate another class, however to test in isolation, i need to mock the implementation of the other class constructor. i have tried several approaches, but have been unable to accomplish this.
the example below obviously doesn't work, since it isn't mocking the import from foo.js, but hopefully it shows what i am trying to do
./foo.js
import Bar from './bar.js'
export default class Foo {
bar: undefined
constructor() {
this.bar = new Bar
}
}
./bar.js
export default class Bar {
constructor() {
console.log('i do not want this to run')
}
}
./foo.test.js
import Foo from './foo.js'
import Bar from './bar.js'
jest.mock('./bar.js', () => {
class BarMock {
constructor() {
console.log('i want this to run')
}
}
})
describe('Foo', () => {
it('should...', () => {
const foo = new Foo
expect(foo.bar).toBeInstanceOf(BarMock)
expect(Bar).toBeCalled()
})
})
Just use
jest.mock('./bar.js')
and in case you want the mock to call console.log within the constructor add:
Bar.prototype.constructor.mockImplementation(() => {
console.log('i want this to run')
})
Edit: here's an example
foo.test.js
import Foo from "./foo.js";
import Bar from "./bar.js";
jest.mock("./bar.js");
Bar.prototype.constructor.mockImplementation(() => {
console.log("i want this to run");
});
describe("Foo", () => {
it("should...", () => {
const foo = new Foo();
expect(foo.bar).toBeInstanceOf(Bar);
expect(Bar).toBeCalled();
});
it("should be a mock function", () => {
expect(jest.isMockFunction(Bar)).toEqual(true);
});
});
working setup
I'm not sure if this code below is what you need,
but the following code called the mocked console.log when I run the test
import Foo from './foo.js'
import Bar from './bar.js'
jest.mock('./bar.js')
describe('Foo', () => {
it('should...', () => {
Bar.prototype.constructor.mockImplementation(() => {
console.log('i want this to run')
})
const foo = new Foo
expect(foo.bar).toBeInstanceOf(Bar);
expect(Bar).toBeCalled()
})
})
this is the result

How to change ES6 imported array

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 = [];
};

How to export multiple functions as aliases in ES6

I want to export multiple functions as aliases in ES6.
I exported it like this because I want to use export default but "as" doesn't seem to work.
const fn1 = () => {};
const fn2 = () => {};
export default = {
fn1 as function1,
fn2 as function2,
} // -> not working
How can I do what I want?
What follows export default should be an expression (not a =). So all you need to do after that is use the right syntax for a normal Javascript object:
export default {
function1: fn1,
function2: fn2,
};
I think that is a wrong syntax. Correct use would be without '=' before "{".
export default {
fn1 as function1,
fn2 as function2
}

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

Migrating es5 to es6 export default

I am trying to migrate a code from es5 to es6, I am quite new in both, if someone could help me, I will be very thankful.
es5 version:
lib.js
module.exports = {
foo1: function () {
this.foo2() {
...
}
},
foo2: function () {
...
}
}
main.js
const Lib = require("./lib");
Lib.foo1( { ... });
es6 version - I am trying:
lib.ts
export default {
foo1() {
this.foo2(() => {
...
});
},
foo2(){ ... }
}
main.ts
import * as Lib from "./lib";
Lib.foo1({ ... })
The problem is in my main.ts foo1 can not be resolved.
Any idea or recommendation?
Thank!
It should be just
import Lib from "./lib";
Otherwise, if you use * as notation you could access default export with Lib.default, but this is unnecessary.
I don't understand the following part of your code:
foo1: function () {
this.foo2() {
...
}
}
That seems invalid.
Anyway, do not introduce your own pseudo-module like structure. It's not necessary. lib.js is already a module.
lib.js
export function foo1() {
foo2();
}
export function foo2() { ... }
main.js
import {foo, foo2} from './lib';

Categories

Resources