简体   繁体   中英

Create NPM Module where all Functions can Access Initialized variables

I want to create an NPM module that will have an initialize() function that is first run to initialize some variables to be used in calls to the main modules functions.

My structure would be something like the below.

📄index.js

📂funcFolder

. . . . .|📄 getFunctions.js

Index.js

import axios from "axios";

let API_KEY = "";
let BASE_URL = "";
let isReady = false;

async function initialize(apiKey) {
  API_KEY = apiKey;
  let results = await axios.get(
    `https://api.themoviedb.org/3/configuration?api_key=${API_KEY}`
  );
  BASE_URL = results.data.images.base_url;
  console.log(results);
  isReady = true;
}

function showConfig() {
  console.log("Base_URL", BASE_URL);
}

export * from "./getFunctions";
export { Init, showConfig, isReady, getFuncs };

The getFunctions.js file has a function in it that I want to have access to the variables that are initialized when initialize() is called.

/funcFolder/getFunctions.js

import axios from "axios";

function getMovie(title) {
  return axios
    .get(
      `https://api.themoviedb.org/3/search/movie?query=${title}&api_key=${API_KEY}`
    )
    .then(res => {
      console.log(res);
      return res;
    });
}

export { getMovie };

I hope I have described this well enough for everyone to understand, but if not, let me know what needs clarification.

After posting this, I realized that I could simply export the variables that I wanted to be shared across files and then import them into the files where they are needed.

So for the index.js file

import axios from "axios";

export let API_KEY = "";
export let BASE_URL = "";
export let isReady = false;

async function initialize(apiKey) {
...
};

export * from "./getFunctions";
export { Init, showConfig, isReady, getFuncs };

Then in any files that neede these variables, I could simply import them.

import axios from "axios";
import { API_KEY } from "../index';

function getMovie(title) {
...
}

export { getMovie };

Open to any other ideas also!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM