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
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.
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' .
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.
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.
As you pointed ES6 modules
export const CONNECT_RANGE = connectRange(Range);
And when you want to consume it
import { CONNECT_RANGE } from './myModule';
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With