node.jswebpackdynamic-importwebpack-plugin

Pass variable based on bundle name to webpack source at compile time


I have a scenario where multiple bundle have the same entry point, called index.js

I then inside that file have dynamic import for the respective sub modules by looking on a env variable:

await import("api/" + process.env.API")

The problem with this is that webpack will bundle all files under api/ since it can't know what that dynamic value is at compile time.

The value of process.env.API is actually the same as the name of the bundle. So I've tried to do use the magic comments feature of webpack to get it working:

await import(
/* webpackInclude: [name] */
"api/" + process.env.API")

But according to the documentation, placeholders are only used for chunk names and not for include/exclude feature.

I've also tried using the context replacement plug-in with callback but the context callback contains no information about the bundle name.

Is it possible to somehow define a plug-in or configure a value which would be resolved as the bundle name at compile time?


Solution

  • If you are using the dynamicImport syntax you usually are generating individual chunks. And as far as I understand your question you want to name these chunks depending on the dynamic path variable?

    A way to do that is import(/* webpackChunkName: "[request]" */ 'api/${process.env.API')

    EDIT

    Dynamic chunk names seem to be generated at runtime (at least thats how I explained it to myself), which is why environment variables might not be available. Save your .env variable in a JS variable and load your dynamic import like this:

    const api = process.env.API;
    const module = await import(/* webpackChunkName: "[request]" */ 'api/${api}');
    

    This will output correctly names chunks containing only the module corresponding to the path.

    EDIT 2 (from OP)

    I also had a problem with babel when using the wrong plugin which caused webpack to transpile import statments to require. Solved using: @babel/plugin-syntax-dynamic-import