dynamic `import()` without creating a separate module

Do you want to request a feature or report a bug?


What is the current behavior?

Currently whenever you import() a module, it will create a separate chunk.

What is the expected behavior?

Sometimes you just want lazily import the module, like you would with require back in the day.

If this is a feature request, what is motivation or use case for changing the behavior?

My application has an asynchronous initialization process and I want to lazily import the rest of the application once the initialization is complete.

Author: Fantashit

3 thoughts on “dynamic `import()` without creating a separate module

  1. You could still use require.

    • require: lazy load at compile time.
    • import: lazy load at runtime.

    The difference between the two is that the file required will only be included in the build if it’s used, which will increase the size of your build. There’s not much asynchronicity happening because you still just have a single output file, and the user has to download the entire JS before execution begins.

    With import – which is part of the official ECMA spec – we achieve true asynchronicity because your app bootstraps, and then chunk files are imported dynamically, thus you could defer that import until they’re actually needed. Users download a small file which renders the app’s skeleton, and then loads in the rest of the app.

    To me it sounds like you do in fact want import because you mention asynchronicity. However, as import is part of the official spec, it wouldn’t make sense to diverge from its intended behaviour. For that we could still use require which adheres to how the Node spec expects it to behave.

  2. Interesting — so require is going to stick around? Typescript doesn’t have proper typechecking for it sadly…

Comments are closed.