doberkofler
doberkofler

Reputation: 10341

How to express this Node export in the new es6 module syntax

How would this kind of (re)export be coded in the new es6 module syntax:

math.js

module.exports = {
   PI: 3.14
};

module.js

const myMath = require('./math.js');

function myFunc() {}

module.exports = {
   PI: myMath.PI, // now is this done in es6?
   myFunc: myFunc
};

Upvotes: 0

Views: 324

Answers (2)

thriqon
thriqon

Reputation: 2488

Another way to go is using the reexport functionality offered by ES6:

# math.js
export const PI = 3.14;

# module.js
export {PI} from './mymath.js';

export function myFunc() { /* TODO */ }

Upvotes: 3

Fabio Antunes
Fabio Antunes

Reputation: 22852

There are several ways of doing it, simplest version

math.js

export default {
  PI: 3.14
};

module.js

import myMath from './math.js';

function myFunc() {}

export default {
  PI: myMath.PI,
  myFunc: myFunc
};

A different way of doing it, having multiple exports on your module:

math.js

export const PI = 3.14;
export default {
  PI: PI
};

module.js

import PI from './math.js';

function myFunc() {}

export default {
  PI: PI,
  myFunc: myFunc
};

In this case we are only importing PI from our math module

Note: You have to use a transpiler for this to work, ES6 modules aren't supported by node yet.

Upvotes: 3

Related Questions