所以,我已将export {BLOG} 添加到这些文件中,但如何多次导入BLOG?
您必须为它们使用不同的导入绑定:
import {BLOG as BLOG1} from 'file1.js';
import {BLOG as BLOG2} from 'file2.js';
...然后使用BLOG1 和BLOG2。或者,如果这让您感到困扰,请添加
const BLOG = Object.assign({}, BLOG1, BLOG2);
导入后继续使用BLOG。
如果您有循环依赖项,BLOG1 和 BLOG2 可能不会立即被完全填充。使用真正的import/export,在这种情况下,您收到的对象将具有它们的属性,但这些属性还不会初始化。因此,使用真正的import/export 或良好的模拟,您可以使用访问器属性来处理它:
// In a true ES2015+ module environment, or a simulated one that
// creates the properties up-front like the real one does
const BLOG = (() => {
const b = {};
for (const blog of [BLOG1, BLOG2]) {
for (const key of Object.keys(blog)) {
Object.defineProperty(b, key, {
get(name) {
return blog[name];
}
});
}
}
return b;
})();
(显然,您会将其包装在一个函数中并重用它。)
在模拟模块环境中,它不像真实的那样预先创建属性,您可以使用代理(当然,如果您要在 ES2015 之前的环境中运行它,它不会有Proxy):
const BLOGS = [BLOG1, BLOG2];
const BLOG = new Proxy({}, {
get(target, propName, receiver) {
const b = BLOGS.find(b => propName in b) || target;
return Reflect.get(b, propName, receiver);
}
});
然后,添加到 BLOG1 和 BLOG2 的属性在事后仍然得到正确解析。
为了避免接下来提到的搜索和替换,所有这些都非常麻烦。
但是:不要导出BLOG、as SLaks says,而是导出类并导入它们。当您使用适当的模块时,不需要“命名空间对象”。
export { myClass1 };
和
export { myClass2 };
然后
import { myClass1 } from "file1.js";
import { myClass2 } from "file2.js";
您甚至可以按照自己的定义导出类:
export function myClass1() { /* ... */ }
或者如果使用class 表示法:
export class myClass1 { /* ... */ }
在多个文件中将new BLOG.myClass1 更改为new MyClass1 是一个非常简单的搜索和替换。在 *nix 上,您可以向它抛出 sed 并创建整个目录树...
旁注:JavaScript 中的压倒性约定是构造函数(通常松散地称为“类”,例如,与new 一起使用的函数)以首字母大写字符编写。例如,MyClass1 和 MyClass2。