Search code examples
javascriptgulpecmascript-6object-literal

Best form to make a map of related strings on JavaScript ES6?


I use gulp to manage all my assets of websites. I migrated all my code to ES6. You can see my starter gulpfile here: https://github.com/ramasilveyra/solid-webapp/blob/master/gulpfile.babel.js

And I have doubts whether this is the best way to handle the paths of all differents assets. There is a better form (more practical without functions)? Thanks!

const paths = {
    src: './src',
    dist: './dist',
    assets: {
        src: paths.src + '/assets',
        dist: paths.dist + '/assets'
    },
    scripts: {
        src: () => paths.assets.src + '/scripts',
        dist: () => paths.assets.dist + '/scripts'
    },
    styles: {
        src: () => paths.assets.src + '/styles',
        dist: () => paths.assets.dist + '/styles'
    },
    media: {
        src: () => paths.assets.src + '/media',
        dist: () => paths.assets.dist + '/media'
    },
    fonts: {
        src: () => paths.assets.src + '/fonts',
        dist: () => paths.assets.dist + '/fonts'
    }
};


Solution

  • ES6 will not bring something new for you. But you can split filling object into few statements:

    const paths = {
       src: './src',
       dist: './dist'
    };
    paths.assets = {
        src: paths.src + '/assets',
        dist: paths.dist + '/assets'
    };
    paths.scripts = {
        src: () => paths.assets.src + '/scripts',
        dist: () => paths.assets.dist + '/scripts'
    };
    // ... and so on
    

    Note that object defined via const can be modified in the further operations. If you want prevent changes of any its field, call Object.freeze(paths) after your assignments.