Besides the valid concerns @Rich_Harris has raised, another thing to worry about is the way await
makes it very easy to cause asynchronous work to be scheduled sequentially when it could be parallelised (and hence faster).
Consider the following:
import {getDayOfWeek} from './static-dep';
const dish = getDayOfWeek() === 'friday' ? 'fish' : 'chicken';
const meal = await import(`./dynamic-dep-${dish}`);
const inBrowser = typeof window !== undefined;
const ajax = await import(inBrowser ? './dynamic-dep-browser' : './dynamic-dep-node');
// ...
While it looks nice, it's also inefficient, because the second dynamic dependency won't be requested until the first one is returned, even though they do not depend on each other.
The correct way to write the same code with concurrent loading is:
import {getDayOfWeek} from './static-dep';
const dish = getDayOfWeek() === 'friday' ? 'fish' : 'chicken';
const inBrowser = typeof window !== undefined;
const [meal, ajax] = await Promise.all([
import(`./dynamic-dep-${dish}`),
import(inBrowser ? './dynamic-dep-browser' : './dynamic-dep-node')
]);
// ...
Not quite as nice, is it?
How many people will write the latter version instead of the former?
Note that this is a risk with using await
in any code, not just top-level, but the impact of unnecessarily sequencing dependency loading in particularly worrying.