ES6 export all values from object

前端 未结 9 1747
梦谈多话
梦谈多话 2020-11-28 07:32

Say I have a module (./my-module.js) that has an object which should be its return value:

let values = { a: 1, b: 2, c: 3 }

// \"export values\         


        
相关标签:
9条回答
  • 2020-11-28 08:31

    Every answer requires changing of the import statements.

    If you want to be able to use:

    import {a} from './my-module'           // a === 1
    import * as myModule from './my-module' // myModule.a === 1
    

    as in the question, and in your my-module you have everything that you need to export in one object (which can be useful e.g. if you want to validate the exported values with Joi or JSON Schema) then your my-module would have to be either:

    let values = { a: 1, b: 2, c: 3 }
    let {a, b, c} = values;
    export {a, b, c};
    

    Or:

    let values = { a: 1, b: 2, c: 3 }
    export let {a, b, c} = values;
    

    Not pretty, but it compiles to what you need.

    See: Babel example

    0 讨论(0)
  • 2020-11-28 08:35
    export const a = 1;
    export const b = 2;
    export const c = 3;
    

    This will work w/ Babel transforms today and should take advantage of all the benefits of ES2016 modules whenever that feature actually lands in a browser.

    You can also add export default {a, b, c}; which will allow you to import all the values as an object w/o the * as, i.e. import myModule from 'my-module';

    Sources:

    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

    • http://www.2ality.com/2014/09/es6-modules-final.html

    0 讨论(0)
  • 2020-11-28 08:36

    Exporting each variable from your variables file. Then importing them with * as in your other file and exporting the as a constant from that file will give you a dynamic object with the named exports from the first file being attributes on the object exported from the second.

    Variables.js

    export const var1 = 'first';
    export const var2 = 'second':
    ...
    export const varN = 'nth';
    

    Other.js

    import * as vars from './Variables';
    
    export const Variables = vars;
    

    Third.js

    import { Variables } from './Other';
    
    Variables.var2 === 'second'
    
    0 讨论(0)
提交回复
热议问题