Javascript基于运行时参数在运行中本地导入标头

时间:2018-06-10 13:32:54

标签: javascript jestjs

Python我可以动态在本地导入headers。现在我正在处理通常在客户端上运行的ReactjslocalStorage。现在它已在服务器端运行。问题已解决here 但我不小心将mock类提交给源代码。所以我开始使用process.envlocal 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)

1 个答案:

答案 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。