From 5b08924c026ff21c2857ba5d0f2357eb424ec890 Mon Sep 17 00:00:00 2001 From: Sebastian McKenzie Date: Thu, 16 Oct 2014 09:39:52 +1100 Subject: [PATCH] add customisable extensions to require hook #75 --- README.md | 20 +++++++++++++++++--- lib/6to5/register.js | 32 ++++++++++++++++++++++++++++---- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 15a651e088..45c25a4aa5 100644 --- a/README.md +++ b/README.md @@ -172,8 +172,9 @@ to5.transformFile("filename.js", options, function (err, result) { #### Require hook -All subsequent files required by node will be transformed by 6to5. The polyfill -specified in [Polyfill](#polyfill) is also required. +All subsequent files required by node with the extensions `.es6` and `.js` will +be transformed by 6to5. The polyfill specified in [Polyfill](#polyfill) is also +required. ```javascript require("6to5/register"); @@ -183,7 +184,20 @@ require("6to5/register"); override this by passing an ignore regex via: ```javascript -require("6to5/register")(/regex/) +require("6to5/register")(/regex/); +``` + +You can also customise the file extensions that the require hook will use via: + +```javascript +require("6to5/register")({ + // optional ignore regex + ignoreRegex: /regex/, + + // this will remove the currently hooked extensions of .es6 and .js so you'll + // have to add them back if you want them to be used again + extensions: [".js", ".es6"] +}); ``` ### Browser diff --git a/lib/6to5/register.js b/lib/6to5/register.js index fcf418eb37..d429c24810 100644 --- a/lib/6to5/register.js +++ b/lib/6to5/register.js @@ -2,6 +2,7 @@ require("./polyfill"); var sourceMapSupport = require("source-map-support"); var to5 = require("./index"); +var _ = require("lodash"); sourceMapSupport.install({ retrieveSourceMap: function (source) { @@ -17,12 +18,14 @@ sourceMapSupport.install({ } }); +// + var ignoreRegex = /node_modules/; +var exts = []; var maps = {}; var old = require.extensions[".js"]; -require.extensions[".js"] = -require.extensions[".es6"] = function (m, filename) { +var loader = function (m, filename) { if (ignoreRegex && ignoreRegex.test(filename)) { return old.apply(this, arguments); } @@ -36,6 +39,27 @@ require.extensions[".es6"] = function (m, filename) { m._compile(result.code, filename); }; -module.exports = function (_ignoreRegex) { - ignoreRegex = _ignoreRegex; +var hookExtensions = function (_exts) { + _.each(exts, function (ext) { + delete require.extensions[ext]; + }); + + exts = _exts; + + _.each(exts, function (ext) { + require.extensions[ext] = loader; + }); +}; + +hookExtensions([".es6", ".js"]); + +module.exports = function (opts) { + opts = opts || {}; + if (_.isRegExp(opts)) opts = { ignoreRegex: opts }; + + if (opts.ignoreRegex != null) { + ignoreRegex = opts.ignoreRegex; + } + + if (opts.extensions) hookExtensions(opts.extensions); };