Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a static member of a class?

I am trying to import a static member of a class into a file by just using standard import syntax. To give context:

Destructuring works on the static method of a class:

class Person {
    static walk() {
        console.log('Walking');
    }
}

let {walk} = Person;
console.log(walk); // walk function

However, I thought imports behaved like destructuring assignments. If that's true, then I would expect the following to work. But, when I attempt to import the walk method, it just comes back as undefined:

Destructuring through imports, why doesn't it work?


person.js

export default class Person {
    static walk() {
        console.log('Walking');
    }
}

walker.js

import {walk} from './person';
console.log(walk); // undefined

Since this doesn't seem to work, how can I import a static method from a class to another module?

like image 876
KevBot Avatar asked Sep 16 '25 23:09

KevBot


1 Answers

export default can be mixed with normal exports in ES6. For example :

// module-a.js
export default a = 1;
export const b = 2;

// module-b.js
import a, { b } from "./module-a";
a === 1;
b === 2;

This means that the import brackets are not the same as a destructor assignment.

What you want to achieve is actually not possible in the ES6 specs. Best way to do it, would be to use the destructuring after your import

import Person from "./person";
const { walk } = Person;
like image 104
drinchev Avatar answered Sep 18 '25 17:09

drinchev