I have a JavaScript file which contains the following:
const api = {
call(type, url, data) {
console.log(type + "bar");
},
get(url, query) {
this.call("foo");
}
}
I'm wanting to be able to call api.get() across multiple different files where necessary, but I'm having trouble importing this.
Loading the file alone through import gives me a ReferenceError when I attempt to access the api variable:
import "services/api.js";
console.log(api);
Uncaught ReferenceError: api is not defined
Giving the import a name (of api) returns an Object, but it has no inner methods:
import api from "../../services/api.js";
console.log(api);
console.log(api.get);
Object {}
undefined
What am I doing wrong?
Your api.js is not exporting anything. You should rewrite it to export every of these functions:
export function call(type, url, data) {
console.log(type + "bar");
}
export function get(url, query) {
call("foo");
}
(which is much better than default-exporting an api object literal)
and then you can use it like
import * as api from "../../services/api.js";
console.log(api);
console.log(api.get);
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