搜尋

首頁  >  問答  >  主體

javascript - 在typescript中如何動態export

接觸typescript不久,現在需要把以前的專案用ts重寫一遍,遇到一個問題:
專案中db的orm都需要實例化才能使用,說明比較困難,請看原js程式碼:

    //const Redis =  require('redis')
    let initRedis = function(port, host){
         return new Promise((success, fail) => {
             module.exports.redis = Redis.createClient(port, host);
             success();
         })
    }
    

以下為我轉換的ts程式碼:

    const initRedis = function (port:number, host:string): Promise<void> {
        return new Promise((success,fail)=>{
            export let redis = Redis.createClient(port, host);
            success();
        })
    }

遇到的錯誤:

 error TS1184: Modifiers cannot appear here.

請問 如何才能正確的在執行initRedis方法後再匯出redis?

漂亮男人漂亮男人2789 天前979

全部回覆(3)我來回復

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-26 10:55:08

    雷雷

    使用

    雷雷

    回覆
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:55:08

    這個是做不到的。
    Typescript的模組是標準符合 ES6 的模組標準, import 和 export 都是static的。

    不過你可以用類似下面的程式碼來做一些workaround。

    // dynamic.ts
    
    const _dynamic = {}
    
    export function addDynamic() {
      _dynamic['Redis'] = function () {
        console.log('I am redis')
      }
    }
    
    export const DYNAMIC = _dynamic
    
    // app.ts
    import { addDynamic, DYNAMIC } from '@/models'
    
    addDynamic()
    DYNAMIC['Redis']()

    回覆
    0
  • phpcn_u1582

    phpcn_u15822017-06-26 10:55:08

    可以參考這裡 https://blogs.msdn.microsoft....

    2.4是已經支持了,等下班回家給你寫個範例

    回覆
    0
  • 取消回覆