簡體   English   中英

Typescript運行時模塊加載(使用Webpack)和類似dll的后期綁定

[英]Typescript runtime module loading (with webpack) and dll-like late binding

假設我有越來越多的不同模板可以與react一起使用。 每個模板都extends React.Component並在其子對象周圍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是否可能?

我將如何要求/導入由表達式標識的模塊?

在使用React應用程序時,我遇到了這個問題。 該應用程序分為多個模塊。 在這些模塊中,有一組具有特定屬性的模塊。 這些模塊不能參與Webpack的構建過程。 它們在設計和構建時不存在。 相反,我只知道其出口的形狀。

要使用這些模塊,瀏覽器必須使用加載程序。 RequireJS AMD loader是一個不錯的選擇。

我花了很多時間弄清楚如何使WebPack在異步加載中很好地發揮作用。 這里的關鍵字是requirejs而不是requireimport

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;
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM