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?
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?
Share Improve this question asked Jun 8, 2017 at 15:42 splattrusplattru 6181 gold badge10 silver badges19 bronze badges 1-
You're exporting the object just fine, but are not importing it as an object. Use
import obj from 'module.js';
for that. If you want individual imports, you probably are not looking for an object at all - use named exports as in @MichałPerłakowski's answer – Bergi Commented Jun 8, 2017 at 15:59
2 Answers
Reset to default 9You 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 use export default, then you need not use the bracket. So you import the module like this:
import module from 'module.js';
// access key property
console.log(module.key)
If you want to import your module like import {key, key2} from 'module.js';
, refer to @Michał Perłakowski answer.