1

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.

2 Answers2

3

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

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1
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()
Jonathan Irwin
  • 5,009
  • 2
  • 29
  • 48
  • i tried this, it doesnt work the way i want, i want to be able to access foo() and foo.bar() without named exports. – Auston Barboza Feb 21 '19 at 15:47
  • @AustonBarboza I have edited my answer so you can do it without named imports. You can only have one default export hence exporting the object with both the functions in it – Jonathan Irwin Feb 21 '19 at 15:55