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.
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.
If a module's primary purpose is to house one specific export, then you should consider exporting it as a default export. This makes both importing and actually using the import a little easier. Further, TypeScript recommends named exports when there are multiple things to export [4].
In ES6, import
s are live read-only views on exported-values. As a result, when you do import a from "somemodule";
, you cannot assign to a
no matter how you declare a
in the module.
However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can’t be changed
counter++; // TypeError
As you can see, the difference really lies in lib.js
, not main1.js
.
To summarize:
import
-ed variables, no matter how you declare the corresponding variables in the module.let
-vs-const
semantics applies to the declared variable in the module.
const
, it cannot be reassigned or rebound in anywhere.let
, it can only be reassigned in the module (but not the user). If it is changed, the import
-ed variable changes accordingly.Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
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