1

I have a main file 'index.js' and I want to import and use the functions in it in another js file.

I tried importing the file using require but it did not work.Can someone help me with suggestion.

Index.js,

   function dcLib() {
       function test() {
          console.log('Hi');
       }
       return {
          test:test
       }
  };
   export default dcLib;

column.js,

   const dcLib = require('../index');
   dcLib.test()    

The above code giving error as

      TypeError: dcLib.test is not a function
pleasent
  • 43
  • 2
  • 9
  • `function dcLib {` - that's invalid syntax - you need `function dcLib() {` and then when you do `dcLib.test()` you still need to execute the function - `dcLib().test()` – VLAZ May 17 '19 at 07:34
  • Function `dcLib` is a function which *when called* returns an object which has a property which is a function. You never call `dcLib`, and it doesn't have a `test` property by itself. – deceze May 17 '19 at 07:36
  • @VLAZ Sory for the typo,edited it.I tried like you said still showing error as dcLib().test() --->dcLib is not a function – pleasent May 17 '19 at 07:39
  • deceze what should be the solution – pleasent May 17 '19 at 07:39
  • @pleasent it largely depends on which transpiler you're using. Default exports changes their import behavior according to many things. In your case, you should probably do `dcLib.default().test()`. If you want that kind of require, you should export an unnamed function instead. You can play around here, if you want to : https://stackblitz.com/edit/js-3wwz8a – briosheje May 17 '19 at 07:44
  • @briosheje,it worked like a charm.Thanks a lot and why do i need to keep default() as i ket it in index.js?. – pleasent May 17 '19 at 07:48
  • @pleasent this is how "require" works. You should instead use `import dcLib from './index'` in order to access the default export properly. I've edited the above example (https://stackblitz.com/edit/js-3wwz8a). – briosheje May 17 '19 at 07:55

1 Answers1

1

Either do:

const dcLib = require('../index');
dcLib.default().test();

... or, if you prefere it, you can do:

const dcLib = require('../index').default;
dcLib().test();

Or, in a simpler (ES6) fashion, just do:

import dcLib from './test';
dcLib().test();

ES6 imports and exports behaves differently if you're using require instead of import. Also, things changes a bit according to the environment and, eventually, the transpiler, if any is used. Read more about that here, where Felix Kling made a pretty exhaustive overview about such argument

As mentioned in the comment, I've made a working example to play with on stackblitz, feel free to play around with it with both cases: https://stackblitz.com/edit/js-3wwz8a?file=index.js

briosheje
  • 7,356
  • 2
  • 32
  • 54