[英]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.我想创建一个 NPM 模块,该模块将有一个 initialize() 函数,该函数首先运行以初始化一些要在调用主要模块函数时使用的变量。
My structure would be something like the below.我的结构如下所示。
📄index.js 📄index.js
📂funcFolder 📂func文件夹
. . .
. .
. .
. .|📄 getFunctions.js
.|📄 getFunctions.js
Index.js索引.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. getFunctions.js 文件中有一个函数,我想访问调用 initialize() 时初始化的变量。
/funcFolder/getFunctions.js /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所以对于 index.js 文件
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!对任何其他想法也持开放态度!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.