[英]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. 我在使用browserify和require以及modules.export语法。 But I want to use ES6 syntax.
但我想使用ES6语法。
How can I do it? 我该怎么做? Thank you.
谢谢。
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. 此外,Rollup项目主页有一个很好的游乐场来测试es6模块的工作原理。 See this example .
看这个例子 。
You can make a factory: 你可以做一个工厂:
//config.js
export function createConfig(ext) {
return Object.assign(
{},
{
a: 'fsdf',
b: 56,
c: 'fsfsdfsd',
set (prop, val) {
this[prop] = val;
}
},
ext
);
};
//index.js
import { createConfig } from './config';
let config = createConfig({
d: 34,
e: 'qqwqw'
});
export config;
// x.js
import { config } from './index.js';
var x = config.d + config.b;
config.set('a', 'asdf');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.