我曾经遇到过类似的情况,我需要通过变量进行导入,但这仅限于在组件内导入组件并且它使用代码拆分(编辑:我正在寻找解决方案而不依赖于代码拆分,我刚刚意识到问题中有一个 react-native 标签,我不认为代码拆分是 RN 中的好选择)。我不确定我的方法对你有多大帮助,但这里有。
旁注:
- 包含
index.js(jsx|ts|tsx)
文件的导入文件夹应自动解析为该index
文件。
- 从通常导入
from './login/index.js'
会引发“未找到模块”错误。要么导入from './login/index'
,要么from './login
但我更喜欢最后一个,因为它是最短和最简单的。
在path.json
:
{
"main": "./login", // '.js' is removed
"paths": [
{
"name": "login",
"path": "./login/index.js", // Not sure what this is for, but if necessary, remove the '.js' here as well
"image": ""
}
]
}
在MyComponent.js
:
import React, { lazy, Suspense } from 'react'
import PathJson from './path'
// 1. We need a UI to show while component is being loaded
const Loader = () => <div>{'Loading...'}</div>
// 2. We need a fallback UI if component is not found
const DocUnavailable = () => <div>{'We\'re sorry, but this document is unavailable.'}</div>
// 3. Create a resolver function ('resolver' is just a name I give)
function resolveImport(pathToComponent, FallbackComponent) {
let componentFound = false
let RenderComponent = () => <FallbackComponent /> // Assign fallback first
try {
if (require.resolve(pathToComponent)) {
componentFound = true
}
} catch (e) { } // Kinda hacky, if you don't mind, but it works
if (componentFound) {
// If found, replace fallback with the valid component
RenderComponent = lazy(() => import(pathToComponent))
}
return RenderComponent
}
// 4. Finally, implement it in a component
class MyComponent extends React.Component {
render() {
const componentPath = PathJson.main
const RenderComponent = resolveImport(componentPath, DocUnavailable)
return (
<Suspense fallback={<Loader />}>
<RenderComponent />
</Suspense>
)
}
}
export default MyComponent
参考: