// a STATIC table with importsconstlanguages={'en':()=>import('./i18n/en'),// it's probably a json...'de':()=>import('./i18n/de'),}// just a helper functionconstpickLanguage=(lng)=>languages[lng];// your componentconstMyI18nProvider=({lng,children})=>{// let's pick and provide correct import function for our languageconst{imported:messages={}// defaulting to empty object}=useImported(pickLanguage(lng));// set messages to the Providerreturn<I18nProvidervalue={messages}>{children}</I18nProvider>
}
import{importedModule,ImportedModule}from'react-imported-component';// you can use it to codesplit and use `momentjs`, no offence :)constMoment=importedModule(()=>import('moment'));<Momentfallback="long time ago">{(momentjs/* default imports are auto-imported*/)=>momentjs(date).fromNow()}</Moment>
// or, again, translations<ImportedModuleimport={()=>import('./i18n/en')}// fallback="..." // will throw to the Suspense boundary without fallback provided>{(messages)=><I18nProvidervalue={messages}>{children}</I18nProvider> }
</ImportedModule>
constComponent=importedComponent(()=>import('./Component'),{LoadingComponent:Spinner,// what to display during the loadingErrorComponent:FatalError// what to display in case of error});Component.preload();// force preload// render it<Component.../>
额外物品
Create React App 支持
关于加拿大税务局(CRA),您应该了解以下三件事:
更改项目配置很困难,因此建议您不要这样做。
它支持SSR或预渲染
这使得更好的代码拆分变得有点复杂。
然而,虽然其他对 SSR 友好的代码分割解决方案需要babel和webpack插件才能工作,但react-imported-component它不需要 webpack 的任何功能,它与打包器无关,并且提供了一个babel 宏,这是唯一一个可以与 CRA 开箱即用的功能。
实现脚本重新加载的第一种方法是提高加载效率。imported-component它提供了一个独立的入口点,/boot在主脚本执行之前启动初始化过程,从而提前加载延迟加载的脚本。这对于 CRA 或 Parcel 来说是一个很好的解决方案,因为在这些平台上,您可能不知道要内联到 HTML 中的代码块文件的真实名称(未安装额外插件)。
import"../async-requires";import{injectLoadableTracker}from"react-imported-component/boot";// ^ just 1kb// injects runtimeinjectLoadableTracker('importedMarks');// give browser a tick to kick off script loadingPromise.resolve().then(()=>Promise.resolve().then(()=>{// the rest of your application// imported with a little "pause"require('./main')}));