ES6 - Exporting module with a getter

后端 未结 2 605
走了就别回头了
走了就别回头了 2021-01-18 09:56

would like to export a module that get\'s the module\'s definition from some global object.

It\'s something like:

export {
  get DynamicModule() {
           


        
2条回答
  •  猫巷女王i
    2021-01-18 10:10

    You can export an object with a getter or export a function if you need to re-evaluate the value every time it is used in imports.

    export const _ = {
      get DynamicModuleGetter() {return __globalFluxStorage.state.property.property.property.property}
    }
    
    export function DynamicModuleFunction() {return __globalFluxStorage.state.property.property.property.property}
    

    Then in import

    import { _, DynamicModuleFunction } from 'dynamic-module'
    
    // getter
    const value1 = _.DynamicModuleGetter
    const {DynamicModuleGetter} = _        // this evaluates the getter
    
    // function
    const value2 = DynamicModuleFunction()
    

    A more elaborate example

    let obj = {
      foo: {
        bar: {
          baz: {
            bak: {
              value: 1
            },
            fak: {
              value: 2
            }
          }
        }
      }
    }
    
    export const _ = {
      get shortcut() {return obj.foo.bar.baz}
    }
    
    export function shortcut() {return obj.foo.bar.baz}
    

    import

    import { _, shortcut } from './shortcut'
    
    let g = _.shortcut.bak.value       // g = 1
    let f = shortcut().fak.value       // f = 2
    let {shortcut: {bak: {value}}} = _ // value = 1
    

提交回复
热议问题