假设我有越来越多的不同模板可以与react一起使用。每个模板extends React.Component
并在其子元素周围呈现精美的边框。
我希望从仅在运行时知道的一些数据动态生成此类模板(带有缓存等)。
在运行时,我可以计算包含模板的模块的名称。我可以将URL映射到服务器代码以提供JavaScript源,并希望浏览器能够运行它。
我想我可以用一种简单的方法来隔离这段代码,类似于通过名称加载* .DLL并调用其导出符号的方法。我的以下猜测无效。
private async templateLoader():Promise<React.ComponentType>{
const templateModuleName:string = this.props.api.getTemplateName(this.props.user);
return (await import(templateModuleName)) as React.ComponentType;
}
我可以想象JavaScript像这样使用require.js
var propsMappedFromStore=this.props;
//...
require(["api","user"],function(api,user){
var templateModuleName = api.getTemplateName(user);
require([templateModuleName],function(tt){
propsMappedFromStore.updateTemplate(tt);
})
})
但是Typescript和Webpack是否可能?
我将如何要求/导入由表达式标识的模块?
答案 0 :(得分:0)
在使用React应用程序时,我遇到了这个问题。该应用程序分为多个模块。在这些模块中,有一组具有特定属性的模块。这些模块不能参与Webpack的构建过程。它们在设计和构建时不存在。相反,我只知道它们的出口形状。
要使用这些模块,浏览器必须使用加载程序。 RequireJS
AMD加载程序是一个不错的选择。
我花了很多时间弄清楚如何使WebPack在异步加载中很好地发挥作用。这里的关键字是 requirejs ,而不是 require 或 import 。
requirejs的使用可以消除webpack.config.js的任何魔力或任何其他魔力。 下面的代码应该给您一个想法。使用语句 requirejs([“ locs /” + lang]…)会导致在 / {baseUrl} / locs / {lang} .js 处的http请求,该请求由Web服务器根据它的灵巧性。
import { getLanguage, IGreetingFormatStrings } from "./lociface";
import { defGeetings } from "./config";
function getGreetings(lang: string): Promise<IGreetingFormatStrings> {
return new Promise((resolve) => {
requirejs(["locs/" + lang]
, (m) => { resolve(m.locGreetings as IGreetingFormatStrings); }
, () => { resolve(defGeetings) }
)
});
}
export async function greeter(person: string): Promise<string> {
const hours = new Date().getHours();
const greetings = await getGreetings(getLanguage());
if (hours > 6 && hours < 12) {
return greetings.morning + person;
}
if (hours < 19) {
return greetings.afternoon + person;
}
return greetings.night + person;
}