在Python
我可以动态在本地导入headers
。现在我正在处理通常在客户端上运行的Reactjs
和localStorage
。现在它已在服务器端运行。问题已解决here
但我不小心将mock
类提交给源代码。所以我开始使用process.env
以local import
Python
的package.json
{
...,
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
我知道如何使用this中的process.env
。但我仍然无法摆脱这个问题。我得到了'import' and 'export' may only appear at the top level
export const getAuthToken = () => {
if (process.env === 'development'){
import localStorage from './localStorageMock';
}
return localStorage.getItem('authToken');
};
问题:
如何在Python
中进行本地导入,例如Javascript
?
如果不能,我该如何解决这个问题?
Attempt1:
localStorageMock2.js
。我尝试了另一种语法。
function LocalStorageMock(){
this.store = {};
this.getItem = function(key){
return this.store[key] || null
};
this.setItem = function(key, value) {
this.store[key] = value
};
this.removeItem = function(key) {
delete this.store[key]
};
}
const localStorageMock = new LocalStorageMock(); export default localStorageMock;
Trackback1:
当我查看cache
对象时
console.log(cache);
{ default:
LocalStorageMock {
store: {},
getItem: [Function],
setItem: [Function],
removeItem: [Function] } }
我想我看到了removeItem
功能。但没有运气。
console.log(typeof cache.removeItem);
undefined
然后就像我预料的那样。它提出了例外。
return cache.removeItem('authToken');
console.error node_modules/redux-saga/lib/internal/utils.js:240
uncaught at askBackend TypeError: cache.removeItem is not a function
at Object.<anonymous>.exports.removeAuthToken (/Users/sarit/study/HT6MInterface/f1/src/utils.js:50:16)
at Object.<anonymous>.exports.VerifyTokenReducer (/Users/sarit/study/HT6MInterface/f1/src/containers/reducers.js:20:34)
答案 0 :(得分:0)
非常感谢him。他总是通过gitter频道支持新手。这是我问题的完整解决方案。
export const myCache = () => {
//Fix the test when runner is on serverside
const tmp = Object.assign({}, process.argv);
const cache = (tmp[4] === '--env=jsdom') ? require("./localStorageMock2") : localStorage;
if (tmp[4] === '--env=jsdom') {
const cache = require("./localStorageMock2");
return cache.default;
} else {
return localStorage;
}
};
我完全忘了require
语法。因为我正在练习纯ES6。