What is the correct way to dynamically import a class inside of a Firebase Cloud function using typescript?

前端 未结 1 1456
Happy的楠姐
Happy的楠姐 2021-01-16 02:35

In a Firebase Cloud Function project...

I have the following typescript file at the root of my src directory right along side of my mai

1条回答
  •  隐瞒了意图╮
    2021-01-16 02:56

    The top-level import (import BcryptTool from './bcrypt.class';) will automatically import the default export from the bcrypt.class module. However, when using the import statement as a function (so called "dynamic import"), it will import the module itself, not the default export.

    You can see the difference when you would console.log(BcryptTool) both imports:

    • import BcryptTool from './bcrypt.class' will show { default: { [Function: BcryptTool] hashValue: [Function], compare: [Function] } }
    • const BcryptTool = await require('bcrypt.class') will show { [Function: BcryptTool] hashValue: [Function], compare: [Function] }

    Did you notice the default in the first console.log? That shows you imported the module, not the default.

    Now actually the import BcryptTool from './bcrypt.class' syntax is syntactic sugar for doing import { default as BcryptTool } from './bcrypt.class'. If you apply this knowledge on the dynamic import, you could do this:

    const BcryptToolModule = await import('./bcrypt.class');
    BcryptToolModule.default.compare(...);
    

    Or in a cleaner syntax:

    const { default: BcryptTool } = await import('./bcrypt.class');
    BcryptTool.compare(...);
    

    0 讨论(0)
提交回复
热议问题