I am trying to import a static member of a class into a file by just using standard import syntax. To give context:
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
:
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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With