So, I've added export {BLOG} to these files, but how can I import BLOG multiple times?
You'd have to use different import bindings for them:
import {BLOG as BLOG1} from 'file1.js';
import {BLOG as BLOG2} from 'file2.js';
...then use BLOG1 and BLOG2. Or if that bothers you, add
const BLOG = Object.assign({}, BLOG1, BLOG2);
after the imports and keep using BLOG.
If you have cyclic dependencies, it's possible that BLOG1 and BLOG2 may not be fully-populated right away. With true import/export, in that situation, the objects you receive will have their properties, but those properties won't be initialized yet. So with true import/export or a good simulation, you could use accessor properties to handle it:
// 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;
})();
(Obviously, you'd wrap that in a function and reuse it.)
In a simulated module environment that doesn't create the properties up-front like the real one would, you could use a proxy (though of course, if you're going to run this in a pre-ES2015 environment, it won't have 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);
}
});
Then, properties added to BLOG1 and BLOG2 after-the-fact still get resolved correctly.
All of which is an awful lot of bother just to avoid the search-and-replace mentioned next.
But: Instead of exporting BLOG, as SLaks says, export the classes, and import those. There's no need for a "namespace object" when you're using proper modules.
export { myClass1 };
and
export { myClass2 };
and then
import { myClass1 } from "file1.js";
import { myClass2 } from "file2.js";
You can even export the class as you define it, either:
export function myClass1() { /* ... */ }
or if using class notation:
export class myClass1 { /* ... */ }
Changing new BLOG.myClass1 to new MyClass1 across multiple files is a really simple search-and-replace. On *nix, you could throw sed at it and do an entire directory tree...
Side note: The overwhelming convention in JavaScript is that constructor functions (often loosely called "classes," e.g., functions you use with new) are written with an initial upper case character. E.g., MyClass1 and MyClass2.
BLOG.myClass1toMyClass1(using standard naming conventions) is a really simple search-and-replace. On any *nix, you could throwsedat it...