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.
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.
16.3 The basics of ES6 modules. There are two kinds of exports: named exports (several per module) and default exports (one per module).
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.
exports and module. exports both point to the same object. exports is a variable and module. exports is an attribute of the module object.
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.
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