Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 413
jhodgson4 Avatar asked May 12 '17 12:05

jhodgson4


People also ask

How do you export constants?

Use named exports to export constants in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported constants can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.

How do you export a constant in React?

To import a constant from another file in React: Export the constant from file A , e.g. export const str = 'First' . Import the constant in file B as import {str} from './another-file' .

What is export default in ES6?

Export Default is used to export only one value from a file which can be a class, function, or object. The default export can be imported with any name.

What does export const mean in JavaScript?

export const is a named export that exports a const declaration or declarations. To emphasize: what matters here is the export keyword as const is used to declare a const declaration or declarations. export may also be applied to other declarations such as class or function declarations.


3 Answers

As you pointed ES6 modules

export const CONNECT_RANGE = connectRange(Range);

And when you want to consume it

import { CONNECT_RANGE } from './myModule';
like image 199
Ematipico Avatar answered Oct 08 '22 15:10

Ematipico


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.

like image 22
Alex Faunt Avatar answered Oct 08 '22 15:10

Alex Faunt


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)

like image 4
nima Avatar answered Oct 08 '22 17:10

nima