How to dynamically export in typescript - Stack Overflow
漂亮男人
漂亮男人 2017-06-26 10:53:08
0
3
947

I came into contact with typescript not long ago, and now I need to rewrite the previous project using ts. I encountered a problem:
The ORM of the db in the project needs to be instantiated before it can be used. The explanation is difficult. Please look at the original js code:

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

The following is the ts code I converted:

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

Error encountered:

 error TS1184: Modifiers cannot appear here.

How can I correctly export redis after executing the initRedis method?

漂亮男人
漂亮男人

reply all(3)
女神的闺蜜爱上我
// xxx.ts
export function initRedis() {}

use

import { initRedis } from 'xx';
扔个三星炸死你

This is impossible.
Typescript modules are in compliance with the ES6 module standard, and both import and export are static.

But you can use code like the following to do some workarounds.

// 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']()
phpcn_u1582

You can refer here https://blogs.msdn.microsoft....

2.4 is already supported. I’ll write you an example when I get home from work

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!