jhodgson4
jhodgson4

Reputation: 1656

What is the correct way to export a constant in ES6?

I'm trying to break my entry file into components but I'm not sure how to make the constant available to the import. This is what I've tried so far and both seem to work:

export const ConnectedRange = connectRange(Range);

exports.ConnectedRange = connectRange(Range);

I've seen the latter used in some npm packages but sure what to use?

Thanks

Upvotes: 41

Views: 82200

Answers (3)

Alex Faunt
Alex Faunt

Reputation: 589

export const ConnectedRange = connectRange(Range);

Is the ES modules syntax.

exports.ConnectedRange = connectRange(Range);

Is the commonJS syntax.

I would recommend using the ES modules syntax, and compiling to common JS if the environment you run your code on does not support ES modules.

Upvotes: 26

nima
nima

Reputation: 8925

With considering all the above answers, you can also export your constant as well as a module in ES6:

module.exports = yourConstant;

and call it from your file:

import yourConstant (JavaScript)

require yourConstant (Node JS)

Upvotes: 6

Ematipico
Ematipico

Reputation: 1244

As you pointed ES6 modules

export const CONNECT_RANGE = connectRange(Range);

And when you want to consume it

import { CONNECT_RANGE } from './myModule';

Upvotes: 54

Related Questions