babel重新连接不替换fetch变量

时间:2018-02-28 20:39:15

标签: node.js module require babel

我已将babel-plugin-rewire的问题与这几个文件分开了。我想弄清楚为什么console.log(dep)仍然将fetch记录为函数而不是true,因为它应该被替换。

  

.babelrc

{
  "presets": [
    "babel-preset-stage-3",
    [
      "babel-preset-env",
      {
        "targets": {
          "node": "4.0.0"
        }
      }
    ]
  ],
  "plugins": [
    "babel-plugin-rewire"
  ]
}
  

dep.js

const fetch = require('isomorphic-fetch')

module.exports = {fetch}
  

use.js

const dep = require('./dep')

dep.__Rewire__('fetch', true)

console.log(dep)
  

的package.json

{
  "scripts": {
    "start": "babel-node ./use.js"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-plugin-rewire": "^1.1.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-3": "^6.24.1"
  },
  "dependencies": {
    "isomorphic-fetch": "^2.2.1"
  }
}

1 个答案:

答案 0 :(得分:0)

好的,刚刚学会了rewire没有改变模块范围(duh)的艰难方法。

  

dep.js

var Path = require('path');

var env = 'production';

console.log(env)

module.exports = function(name) {
  console.log(env)
  return Path.normalize(name)
}
  

use.js

var normalizer = require('./dep.js');

normalizer.__Rewire__('Path', {
  normalize: (name) => name
});

console.log(normalizer('/foo/bar//baz/asdf/quux/..'))

normalizer.__Rewire__('env', 'testing');

console.log(normalizer('/foo/bar//baz/asdf/quux/..'))

normalizer.__ResetDependency__('Path');

console.log(normalizer('/foo/bar//baz/asdf/quux/..'))

日志:

production
production
/foo/bar//baz/asdf/quux/..
testing
/foo/bar//baz/asdf/quux/..
testing
/foo/bar/baz/asdf