我的測驗首先運行良好,我現在使用基于視窗物件的環境變數,例如:
{window._env_.REACT_APP_URL}
但是當我運行測驗時:它顯示為TypeError: Cannot read property 'REACT_APP_URL' of undefined
當我更改為{process.env.REACT_APP_URL}一切按預期作業時,我是否需要在我的測驗檔案中做一些不同的事情來接受這種型別的變數?
有任何想法嗎?
uj5u.com熱心網友回復:
開箱即用_env_的物件上不存在該屬性,因此 TypeScript 抱怨您正在為屬性分配值。windowundefined
解決問題的最佳方法是將window變數重新分配給將當前window型別與您自己的自定義EnvironmentVariables界面相結合的自定義變數,并在您的測驗中使用它:
interface EnvironmentVariables {
'_env_': {
'REACT_APP_URL': string
}
}
const customWindow = window as Window & typeof globalThis & EnvironmentVariables;
// set the _env_ object with values
customWindow._env_ = {
'REACT_APP_URL': 'url here'
}
// access REACT_APP_URL
customWindow._env_.REACT_APP_URL
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453633.html
標籤:javascript 反应 单元测试 开玩笑的
上一篇:錯誤AttributeError:'function'objecthasnoattribute'json'從其他檔案匯入函式時發生
