I have several modules of styled components in a file exported which I want to dynamically import into another file.
I learned to import a module we have to do this
const Heading = dynamic(
() => import("./style").then((module) => module.Heading),
{
ssr: false,
}
);
how can I import all the modules at once instead of importing them separately for every module from the same file
What I want to achieve is something like this but it gives me error to load all components in single import
const {Heading , CustomError }= dynamic(
() => import("./style").then((module) => module),
{
ssr: false,
}
);
Caveat: I don't use Next.js (yet?). But trying to help anyway:
I think the nature of dynamic is that it creates and returns a single component facade when you call it, so you'll have to make multiple calls to dynamic. But that doesn't mean you have to repeat everything. Unless dynamic is a pseudo-function that's replaced at build time, you can give yourself a helper to do the heavy lifting:
const dynamicStyle = (name) => dynamic(
() => import("./style").then((module) => module[name]),
{ ssr: false }
);
Then at least each component is simpler and not (that) repetitive:
const Heading = dynamicStyle("Heading");
const CustomError = dynamicStyle("CustomError");
About this:
how can I import all the modules at once instead of importing them separately for every module from the same file
I suspect you meant "...for every component from the same file..." In case you're worried about the module being imported multiple times, don't be. Regardless of how many times you call import("./style"), the module is only imported once. If the module is already imported or being imported the second/third/fourth time you call import(), the promises from those calls just get fulfilled with the same module namespace object that the first one did/will. That's effectively guaranteed by the specification where it says:
Any subsequent call to HostResolveImportedModule after FinishDynamicImport has completed, given the arguments referencingScriptOrModule and specifier, must return a normal completion containing a module which has already been evaluated, i.e. whose Evaluate concrete method has already been called and returned a normal completion.