Skip to content
This repository has been archived by the owner on May 24, 2019. It is now read-only.

Use pirates for interoperability with other require hooks #62

Merged
merged 1 commit into from
Feb 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
],
"dependencies": {
"babylon": "^6.15.0",
"pirates": "^3.0.2",
"vlq": "^0.2.1"
},
"engines": {
Expand Down
37 changes: 12 additions & 25 deletions register.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var flowRemoveTypes = require('./index');
var pirates = require('pirates');

// Supported options:
//
Expand All @@ -13,34 +14,20 @@ module.exports = function setOptions(newOptions) {
options = newOptions;
}

// Swizzle Module#_compile on each applicable module instance.
// NOTE: if using alongside Babel or another require-hook which simply
// over-writes the require.extensions and does not continue execution, then
// this require hook must come after it. Encourage those module authors to call
// the prior loader in their require hooks.
var jsLoader = require.extensions['.js'];
var exts = [ '.js', '.mjs', '.jsx', '.flow', '.es6' ];
exts.forEach(function (ext) {
var superLoader = require.extensions[ext] || jsLoader;
require.extensions[ext] = function (module, filename) {
if (shouldTransform(filename, options)) {
var super_compile = module._compile;
module._compile = function _compile(code, filename) {
try {
var patched = flowRemoveTypes(code, options);
}
catch (e) {
e.message = filename + ': ' + e.message;
throw e;
}
super_compile.call(this, patched.toString(), filename);
};
}
superLoader(module, filename);
};
});

function shouldTransform(filename, options) {
var revert = pirates.addHook(function hook(code, filename) {
try {
return flowRemoveTypes(code, options).toString();
}
catch (e) {
e.message = filename + ': ' + e.message;
throw e;
}
}, { exts: exts, matcher: shouldTransform });

function shouldTransform(filename) {
var includes = options && regexpPattern(options.includes || options.include);
var excludes =
options && 'excludes' in options ? regexpPattern(options.excludes) :
Expand Down