Utilizing the try
-catch
is effective with standard JavaScript in various environments such as the browser and Node:
try {
const { ModuleLayout } = await import('path-to-module').catch(reason => { })
if (ModuleLayout) {
console.log(ModuleLayout);
}
}
catch (error) {
console.log('error');
}
Interestingly, the presence of .catch
in this context is deemed unnecessary.
It seems that the complication arises due to Next conducting additional analysis on imports via WebPack:
https://github.com/webpack/webpack/issues/6680#issuecomment-370800037
One suggestion is to restrict the path to a recognized directory, although this may not be suitable for all scenarios. Consider raising an issue on the Next repository to propose the inclusion of a feature that allows disabling static analysis for specific imports, if it aligns with your use case.
For more information on dynamic import in Next, refer to the official documentation:
https://nextjs.org/docs/advanced-features/dynamic-import#example
Please note: The path in import('path/to/component')
must be explicitly stated and cannot be a template string or variable. Additionally, the import()
function must be enclosed within the dynamic()
call for Next.js to successfully match webpack bundles/module ids to the specific dynamic()
call in order to preload them before rendering. Use of dynamic()
within React rendering is limited to the top level of the module to enable preloading, similar to React.lazy
.
No clear solution is provided on how to overcome this limitation and achieve a genuinely dynamic export during runtime.
According to a user's experience here, wrapping the import
statement in dynamic
proved to be effective for resolving the issue.