Search code examples
javascriptwebpackes6-module-loaderes6-modules

How can I export static class methods without exporting the whole class


I am creating a node package to handle cookies. What is the best way to export static class methods from the class below?

export default class Cookies {
    static get (name) {...}
    static set (...) {...}
    static remove (...) {...}
}

And is it then possible to import them like this, so people don't have to import the remove method if they don't need it?

import { get, set } from "Cookies"


Solution

  • Since they are static methods, they are basically just properties on the class object. Since that is the case, you can just export them one by one:

    export default class Cookies {
        static get (name) {...}
        static set (...) {...}
        static remove (...) {...}
    }
    
    export const get = Cookies.get;
    export const set = Cookies.set;
    export const remove = Cookies.remove;