1

justExport.js

const first = () => {
  console.log('frist from justExport')
}

const second = () => {
  console.log('second fromt justExport')
}

module.exports = {
  first,
  second,
}

tmp.js

module.exports = {
  ...require('./justExport') // work
  require('./justExport') // SyntaxError: Unexpected string
}

main.js

const justExport = require('./justExport.js')
const tmp = require('./tmp.js')

console.log('Hello World!')

I have voluntarily create a fake example with the less possible code.

S7_0
  • 1,165
  • 3
  • 19
  • 32

2 Answers2

2

{ ...require('./justExport') } is object literal spread. While { require('./justExport') } is incorrect object literal syntax because it doesn't contain a key.

Unless the intention is to create shallow copy of justExport module, object literal isn't needed. It can be:

module.exports = require('./justExport');
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • How can I verify that require('./justExport') is an incorrect object ? Because I though that require() return an object create by module.export(), so if it's an object, it should contain a key/value notation right ? (tell me if I don't use the correct term or don't explain me well) – S7_0 Jan 07 '19 at 14:42
  • I didn't say its incorrect object. `{ require('./justExport') }` is incorrect *syntax*. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer for all possible syntax variations. `require('./justExport')` expression is already an object. It doesn't need to be wrapped with braces. – Estus Flask Jan 07 '19 at 14:46
  • I read the Syntax part of the link you posted. Does { require('./justExport') } is incorrect syntax because require return something like { key: value } but module.export expect something module.export { key { key: value } } ? – S7_0 Jan 07 '19 at 15:27
  • It's incorrect syntax because correct syntax is either `{ ...value }`, or `{ key: value }`, or `{ value }` (the latter is shorthand for `{ value: value }`). It doesn't matter what `require()` returns if you don't use correct syntax. – Estus Flask Jan 07 '19 at 15:38
1

To further clarify the answer from @estus, note that the following works due to ES6 shorthand property names:

const justExport = require('./justExport');

module.exports = {
  ...justExport, // works
  justExport // works because key is implicitly defined by variable name
}
nareddyt
  • 1,016
  • 10
  • 20
  • Does module.exports { require('./justExport') } doesn't work because require return an object with any key that "point to that object (return by require )? – S7_0 Jan 07 '19 at 15:08