javascriptpolymerbabeljsstatic-import

JavaScript export imports at random behaviour in Polymer PWA Starter Kit


I am having a file that serves as a server-mockup, importing all other services and exporting them, so I only have to have a single import in other files, like so:

import * as User from './user.js';
import * as Service from './service.js';

export { User, Service };

Now each of these services simply exports some constants. Like so:

export const registeredUsers = [

]

I want to achieve to use something like Server.User.registeredUsers in other files. This is somewhat working, my component imports the Server like so:

import * as Server from '../../mockup/server.js';

Side-note: I am using the PWA-Starter-Kit: https://github.com/Polymer/pwa-starter-kit

Now I encounter the following problematic situation:

I am importing * as Server like shown above and the resulting Object sometimes has a default attribute. That means sometimes I must access Server.User and sometimes Server.default.User. This seems completely random.

I made a workaround like this:

let User = Server.User || Server.default.User;

this will always work. But it's a little hacky as the behaviour seems unpredictable. I'd like to adjust this. What might be the problem here and how could I solve it?

I have already tried to define the export in server.js as default.

server.js

import * as User from './user.js';
import * as Service from './service.js';

export default { User, Service };

and import like so:

import Server from '../../mockup/server.js';

Resulting in the same issue.

For me this is a very interesting problem, what might be the reason? The occurance when to use Server.default.User and Server.User is absolutely random. I can go on refreshing the page and it will change its behaviour from time to time (sometimes on every refresh, sometimes only after 3 or more).

I might not really use this huge import/export file for production anyway, but I would still like to solve this problem. For the sake of curiosity.

edit:

console.log(Server);
console.log(Server.Service);

Resulting in:

non-default

or:

default


Solution

  • The problems described above occurred as a result of bad dynamic importing. Somewhere else in my project I had two dynamic imports, where one of them was a parent of the other one. The "random" occurrance described above was the result of whether the first or the second import won the race (although why it resulted in the way it did is puzzling me).

    This means I had to make sure import1 came before import2, which I simply solved with

    await import('dynamic import1');
    

    This solved the issue above.

    Maybe this will help someone else stumbling upon this problem.