I have the following code:
module.exports = {
key: "value",
key2: 1234
}
If I change it to:
export default {
key: "value",
key2: 1234
}
Then the following import stops working:
import {key, key2} from 'module.js';
What is an ES6 equivalent of exporting an object?
All CommonJS and AMD modules are presented to ES6 as having a default export, which is the same thing that you would get if you asked require() for that module—that is, the exports object. ES6 modules were designed to let you export multiple things, but for existing CommonJS modules, the default export is all you get.
With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.
The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import.
Modules are the piece or chunk of a JavaScript code written in a file. JavaScript modules help us to modularize the code simply by partitioning the entire code into modules that can be imported from anywhere. Modules make it easy to maintain the code, debug the code, and reuse the piece of code.
You can first define the variables and export them:
const key = 'value';
const key2 = 1234;
export { key, key2 };
Or you can export them in the same line in which you define them:
export const key = 'value';
export const key2 = 1234;
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