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

Commit

Permalink
Merge pull request #62 from anandthakker/pirates
Browse files Browse the repository at this point in the history
Use pirates for interoperability with other require hooks
  • Loading branch information
motiz88 authored Feb 19, 2019
2 parents 48a31b1 + 167a43a commit 65f108e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 25 deletions.
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

0 comments on commit 65f108e

Please sign in to comment.