【问题标题】:Create NPM Module where all Functions can Access Initialized variables创建所有函数都可以访问初始化变量的 NPM 模块
【发布时间】:2020-01-02 18:25:49
【问题描述】:

我想创建一个 NPM 模块,该模块将具有一个 initialize() 函数,该函数首先运行以初始化一些变量,以便在调用主模块函数时使用。

我的结构如下所示。

??????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 };

getFunctions.js 文件中有一个函数,我想访问在调用 initialize() 时初始化的变量。

/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 };

我希望我已经描述得足够好让每个人都能理解,但如果没有,请告诉我需要澄清的地方。

【问题讨论】:

    标签: javascript npm module scope


    【解决方案1】:

    发布后,我意识到我可以简单地导出我想跨文件共享的变量,然后将它们导入到需要它们的文件中。

    所以对于 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 };
    

    然后在任何需要这些变量的文件中,我可以简单地导入它们。

    import axios from "axios";
    import { API_KEY } from "../index';
    
    function getMovie(title) {
    ...
    }
    
    export { getMovie };
    

    也欢迎任何其他想法!

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 2015-09-20
      相关资源
      最近更新 更多