Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a namespace?

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.

  1. 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

  2. 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?

like image 915
James Donnelly Avatar asked Nov 26 '25 14:11

James Donnelly


1 Answers

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);
like image 149
Bergi Avatar answered Nov 28 '25 02:11

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!