使用Node.js更好的方式来require.extensions

我正在testing一堆React JSX组件。 他们都需要用React或者Babel或者其他方法进行编译,但是我们有特殊的需求,所以我试图用一个与Mocha一起运行的特殊编译器来覆盖需求。 下面的解决scheme运行良好,但是您会注意到我们正在使用require.extensions []来捕获所有的.jsx文件。 我所关心的是require.extensions被locking并被弃用。 有没有更好的方法来做到这一点?

// Install the compiler. require.extensions['.jsx'] = function(module, filename) { return module._compile(transform(filename), filename); }; 

下面是整个转发器供参考:

 // Based on https://github.com/Khan/react-components/blob/master/test/compiler.js var fs = require('fs'), ReactTools = require('react-tools'); // A module that exports a single, stubbed-out React Component. var reactStub = 'module.exports = require("react").createClass({render:function(){return null;}});'; // Should this file be stubbed out for testing? function shouldStub(filename) { if (!global.reactModulesToStub) return false; // Check if the file name ends with any stub path. var stubs = global.reactModulesToStub; for (var i = 0; i < stubs.length; i++) { if (filename.substr(-stubs[i].length) == stubs[i]) { console.log('should stub', filename); return true; } } return false; } // Transform a file via JSX/Harmony or stubbing. function transform(filename) { if (shouldStub(filename)) { delete require.cache[filename]; return reactStub; } else { var content = fs.readFileSync(filename, 'utf8'); return ReactTools.transform(content, {harmony: true}); } } // Install the compiler. require.extensions['.jsx'] = function(module, filename) { return module._compile(transform(filename), filename); }; 

和一些simalar解决scheme的链接…

  • https://github.com/danvk/mocha-react/issues/1
  • https://github.com/Automattic/jsx-require-extension
  • https://www.npmjs.com/package/node-jsx
  • https://github.com/olalonde/better-require
  • http://mochajs.org/#usage
  • http://nodejs.org/api/globals.html#globals_require_extensions

解决scheme可以从这里分叉: https : //github.com/danvk/mocha-react

没有其他办法可以做到这一点,这就是每个人如何运输(巴贝尔等)。 @ uni_nake的答案 – 使用node-hook是可以的,因为它隐藏了它,但它本质上使用相同的机制:查看它的代码显示它使用Module._extensions,但是这与require.extensions ,如我所写的testing所示: https : //github.com/giltayar/playing/blob/1f04f6ddc1a0028974b403b4d1974afa872edba4/javascript/node/test/is-module-extensions-same-as-require-extensions.test.js

所以最后的答案是 – 我会假设Node上没有人会打破Babel,如果他们这样做,他们可能会为同样的问题提供另一个解决scheme。 我会毫不犹豫地使用它!

我使用node-hook在我的testing中.scss所有.scss调用。

您将从文档中看到,当需要匹配的文件时,它将执行包含的string,而且function非常强大,因为它也传递给您原始的源文件。

希望这就是你要找的。