3

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?

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
James Donnelly
  • 126,410
  • 34
  • 208
  • 218

4 Answers4

6

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

First you have to export it, as such:

const api = {
  call(type, url, data) {
    console.log(type + "bar");
  },

  get(url, query) {
    this.call("foo");
  }
}

export {api}

And then, import it:

import {api} from './path/to/api' // no .js

This approach is used when you're exporting multiple items (functions, classes, variables) from one file. If in your case api is the only item that you're exporting, you can use the default keyword and you will no longer need to use the accolades during import:

const api = {
  call(type, url, data) {
    console.log(type + "bar");
  },

  get(url, query) {
    this.call("foo");
  }
}

export default api

and

import api from './path/to/api'

Good luck!

motanelu
  • 3,945
  • 1
  • 14
  • 21
1

You need to export your api:

const api = ...

export default api;
Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30
0

As a side note to this: export / import like this is ES6 module spec, be aware. For Node / CommonJS Module environments without any transpiler, it would be

// export
module.exports.api = api

// or
module.exports = { api: api } ...


// import
var module = require(....)