Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export object, extend and re-export it in ES6

I want to define an object with common properties:

var Config = {
  a: 'fsdf',
  b: 56,
  c: 'fsfsdfsd',
  set: function set(prop, val) {
    this[prop] = val;
  }
};

In another file, I want to extend it with custom properties:

var Config = Object.assign(Config, {
  d: 34,
  e: 'qqwqw'
});

And then, I want to read and modify the object in other files:

var x = Config.d + Config.b;
Config.set('a', 'asdf');

At the momment I was using browserify and require and modules.export syntax. But I want to use ES6 syntax.

How can I do it? Thank you.

like image 283
dgnin Avatar asked Dec 21 '15 13:12

dgnin


People also ask

What is the correct way of exporting a component in ES6?

ES6 provides two ways to export a module from a file: named export and default export. With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.

What are the two types of exports in ES6?

16.3 The basics of ES6 modules. There are two kinds of exports: named exports (several per module) and default exports (one per module).

Does module exports work with ES6?

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.

What is the difference between exports and module exports?

exports and module. exports both point to the same object. exports is a variable and module. exports is an attribute of the module object.


1 Answers

Exported variables are bound across modules, so you can modify imported value and it will be changed in other places

//config.js
const Config = {a: 'value1'};
export default Config;

//a.js
import Config from './config';
// you don't need to reassign return value, first argument will be mutated itself
Object.assign(Config, {a: 'value2'}); 

//b.js
import Config from './config';
import './a';

console.log(Config); // prints {a: 'value2'}

This article has more explanations about it.

Also, Rollup project homepage has a great playground to test how es6 modules works. See this example.

like image 136
just-boris Avatar answered Nov 08 '22 15:11

just-boris