search

Home  >  Q&A  >  body text

How to dynamically export in typescript - Stack Overflow

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?

漂亮男人漂亮男人2714 days ago959

reply all(3)I'll reply

  • 女神的闺蜜爱上我

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

    // xxx.ts
    export function initRedis() {}

    use

    import { initRedis } from 'xx';

    reply
    0
  • 扔个三星炸死你

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

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

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-26 10:55:08

    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

    reply
    0
  • Cancelreply