scenes to be used
Many components are encapsulated in a project, and the corresponding components are dynamically loaded in the page according to the interface returning different types of values.
Problem Description
The method of dynamically loading components is used. When the components are introduced with import(), they can be found by directly writing the static path components, but the variable components are used in the path and cannot be found, and the error Error:Cannot find module is reported.
problem causes
The import() syntax is a newly introduced syntax for dynamically loading modules in ES6. It can load modules at runtime and return a Promise object, which can be used to load different modules.
So the import() syntax itself is a function, in which a string can be passed in to represent the path of the module to be loaded, but variables cannot be passed in, because the value of the variable may change at runtime, and the import() syntax It is determined at compile time, so variables cannot be passed in.
solution
Use the require.ensure() method of webpack to introduce components, which can accept variables as parameters and return Promise objects
return () => require.ensure([], (require) => require(`./components/${
type}.vue`))
I hope it is helpful to everyone, and if there is a better way, you can share it! ! !