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?
問題解答
回答1:// xxx.tsexport function initRedis() {}
use
import { initRedis } from ’xx’;回答2:
這個是做不到的。 Typescript的模塊是標準符合 ES6 的模塊標準, import 和 export 都是static的。
不過你可以使用類似下面的代碼來做一些workaround。
// dynamic.tsconst _dynamic = {}export function addDynamic() { _dynamic[’Redis’] = function () { console.log(’I am redis’) }}export const DYNAMIC = _dynamic
// app.tsimport { addDynamic, DYNAMIC } from ’@/models’addDynamic()DYNAMIC[’Redis’]()回答3:
可以參考這里 https://blogs.msdn.microsoft....
2.4是已經支持了,等下班回家給你寫個范例
相關文章:
1. python - 獲取到的數據生成新的mysql表2. javascript - js 對中文進行MD5加密和python結果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. 為什么python中實例檢查推薦使用isinstance而不是type?
