How to access window variable in Javascript object?

醉酒当歌 提交于 2021-02-11 15:37:32

问题


Is the below code correct ? I want to access the window variable in a javascript object.

export const configs={
  //firebase configuration
  apiKey: window._env_.API_KEY,
  projectId: window._env_.PROJECT_ID,
  messagingSenderId: window._env_.MESSAGING_SENDER_ID,
  backendURL: window._env_.BACKEND_URL
}

回答1:


If this code is executed in a browser, window is available as a global object. However, if this code is executed in a node environment (server side), window will be undefined.

Here's one way to handle this if your code will execute both server-side (node environment) and client-side (browser environment):

if (typeof window !== 'undefined') {
  configs = {
    //firebase configuration
    apiKey: window._env_.API_KEY,
    projectId: window._env_.PROJECT_ID,
    messagingSenderId: window._env_.MESSAGING_SENDER_ID,
    backendURL: window._env_.BACKEND_URL
  }
} else {
  // handle server-side logic here
}

If there's no need for this to execute in the browser, it would be simplest to just use process.env instead of setting these variables on the window. If you do need these variables in both places (and they're coming from process.env), this might be another solution:

const env = typeof window === 'undefined' ? process.env : window._env_;

export const configs = {
  //firebase configuration
  apiKey: env.API_KEY,
  projectId: env.PROJECT_ID,
  messagingSenderId: env.MESSAGING_SENDER_ID,
  backendURL: env.BACKEND_URL
}



回答2:


You should create a new js file, then write as below. File name is appsettings.js

window.appSettings = {
    apiKey: '${REACT_API_KEY}',
    projectId: '${REACT_PROJECT_ID}',
    messagingSenderId: '${REACT_SENDER_ID}',
    backendURL: '${REACT_BACKEND_URL}'
};

env files

REACT_API_KEY=value
REACT_PROJECT_ID=value
REACT_SENDER_ID=value
REACT_BACKEND_URL=value

Public/index.html

<script src="http://localhost/appsettings.js?v={version}"></script>
    <script>
        window.appSettings.apiKey= '%REACT_API_KEY%';
        window.appSettings.projectId= '%REACT_PROJECT_ID%';
        window.appSettings.messagingSenderId= '%REACT_SENDER_ID%';
        window.appSettings.backendURL= '%REACT_BACKEND_URL%';
    </script>

Where you want to use, write this code

window.appSettings.apiKey

Not need declare another place because it declare index.html



来源:https://stackoverflow.com/questions/60682955/how-to-access-window-variable-in-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!