node-require-directory icon indicating copy to clipboard operation
node-require-directory copied to clipboard

Add support to ES6 exports

Open markotom opened this issue 8 years ago • 3 comments

I would need to load module with:

export default function () {}

markotom avatar Jun 30 '17 19:06 markotom

Hello @markotom, thank you for your effort!

However, what will happen if I have the below code in my module?

module.exports = {
  foo: 'foo',
  default: {
    foo: 'FOO'
  }
};

So, I'm exporting an object, which has default property. It looks like your implementation will break it and will return only a subset of the exported object. I think to handle it more safely, we will need to distinguish module definition objects and exported plain objects.

I'm not an expert at this matter, but according to this answer on SO babel will define the __esModule property on the exported module.

And here's how it checks for module definition:

obj && obj.__esModule

I think the more safe approach would be to use this code:

obj = obj && obj.__esModule && obj.default ? obj.default : obj;

It's based solely on the answer on SO. You will need to check this against various versions of Babel.

Also, are there other transpilers that we should be aware of? How TypeScript handles this?

slavafomin avatar Jun 30 '17 21:06 slavafomin

I totally agree, __esModule would not be enough. We can use systemjs to accept not only babel, but other transpilers that use es6, commonjs, amd, etc.

markotom avatar Jul 02 '17 02:07 markotom

A custom loader can be passed to the require-directory in the first argument. For example ES6 modules loading using @std/esm:

cli.js

const loader = require('@std/esm')(module)
const requireDirectory = require('require-directory')
const mod = { filename: module.filename, require: loader }

requireDirectory(mod, './data', { extensions: ['mjs'] } )

data/hello.mjs

export const foo = 'bar'

Run the node cli.js:

{ hello: { foo: 'bar' } }

generalov avatar Oct 06 '17 19:10 generalov