Problem with dynamic path in dynamic import!

I tried to using dynamic path in dynamic import

// main.js
let path = 'testing';
import(`../libs/${path}.js`).then(module => {
   let func = module.default;

Get error

Uncaught (in promise) Error: Cannot find module '../libs/testing.js'

Yeah dynamic imports need to be statically declared somewhere for the build tool to make the bundles available.

If you really need dynamic paths (as I do) you can create a whitelist which declares your modules without loading them like so:

if (false) {

I keep a whitelist.js file for this purpose with the modules that are loaded via dynamic paths.

Thanks for your reply.
Excuse me, could you detail how to use this case? I seem don’t understand.

As an example, I work on an app that has many heavy templates which are loaded depending on the content saved in the CMS db.

If I allow them all to be eager loaded, the initial bundle is around 3.5 MB. So I use dynamic imports to load them when required.

Because the templates required are loaded via a database, they are loaded with a dynamic path ie.
const path = db.find(template).path; import(path);

To satisfy the restriction on dynamic imports that they must be statically declared somewhere I create a file called module-whitelist.js that has the static paths of the template files that may be loaded by a dynamic import which looks like the file in the previous post.

Now when someone loads the page, the app loads the content via the db, figures out which templates are required and dynamically loads them.

Using this, the initial app bundle is down to ~400kb and the heavy stuff is only loaded when the content needs it.

1 Like