简体   繁体   English

为什么我不能从另一个文件访问变量?

[英]Why can't I access variables from another file?

In my project, I use WebPackEncore to manage my libraries.在我的项目中,我使用 WebPackEncore 来管理我的库。

in a file I regroup all the keys needed to access API, it's called keys.js :在一个文件中,我重新组合了访问 API 所需的所有密钥,它被称为keys.js

const keys = {
    //> Algolia/places API
    ALGOLIA_PLACE_APP_ID: "appKey",
    ALGOLIA_PLACE_API_ID: "APIkey",
    //###< Algolia/places API

    //> MapBox API
    MAPBOX_TOKEN: "mapBoxToken",
    //< MapBox API
}

in my app.js file I try to use theses keys:在我的app.js文件中,我尝试使用这些键:

import keys from './keys';

//do stuff 

If I try to use a console.log(keys) in my app.js file I get a {} which make it completely useless.如果我尝试在app.js文件中使用console.log(keys) ,我会得到一个{} ,这使它完全没用。

Is it a normal behavior and I miss a scope problem ?这是正常行为,我错过了范围问题吗? Is it a bad way to insert keys (I try to reproduce the behavior of my .env file) ?插入密钥是否是一种糟糕的方式(我尝试重现我的.env文件的行为)?

You're not exporting the variable from keys.js .您不是从keys.js导出变量。 Try like this..试试这样..

export default keys = {
    //> Algolia/places API
    ALGOLIA_PLACE_APP_ID: "appKey",
    ALGOLIA_PLACE_API_ID: "APIkey",
    //###< Algolia/places API

    //> MapBox API
    MAPBOX_TOKEN: "mapBoxToken",
    //< MapBox API
}

The answer of Kelly Copley is alright but that's only if you want to export keys by default. Kelly Copley 的答案是可以的,但前提是您要默认导出keys If you wished to export keys in a modular way, try it like this:如果您希望以模块化方式导出keys ,请尝试如下操作:

export const keys = {
    //> Algolia/places API
    ALGOLIA_PLACE_APP_ID: "appKey",
    ALGOLIA_PLACE_API_ID: "APIkey",
    //###< Algolia/places API

    //> MapBox API
    MAPBOX_TOKEN: "mapBoxToken",
    //< MapBox API
}

Then you import it like this:然后你像这样导入它:

import { keys } from './keys';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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