diff --git a/README.md b/README.md index 46753d6..c192eea 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,21 @@ As of version 0.4, **injectr** doesn't create a full node.js context for you to use. Instead, it isolates your script in its own sandbox, allowing you to include mocks of only the bits that your script needs. +## Configure for Babel ## + +Injectr optionally transpiles babel for `.js` and `.jsx` files. Injectr +automatically reads in `.injectrrc` in the root of your project. For example, +to enable babel transpilation within injectr, simply add `.injectrrc`: + +```json +{ + "babel": true, + "babelOptions": {} +} +``` + +You will need to `npm install --save-dev babel-core` for this to work. + ### CoffeeScript ### **injectr** compiles any *.coffee files for you, so you can test your diff --git a/lib/injectr.js b/lib/injectr.js index 24d2801..8b858c7 100644 --- a/lib/injectr.js +++ b/lib/injectr.js @@ -3,7 +3,30 @@ var cache = {}, fs = require('fs'), path = require('path'), - vm = require('vm'); + vm = require('vm'), + encoding = 'utf8', + OPTION_FILE_NAME = '.injectrrc', + injectrRC, + options = { babel: null, babelOptions: null }; + +/** + * Parse options from .injectrrc if present. + * Injectrrc is expected to be a JSON file. + */ +(function _parseOptions() { + try { + injectrRC = fs.readFileSync( + process.env.PWD + '/' + OPTION_FILE_NAME, + encoding + ); + + try { + options = JSON.parse(injectrRC); + } catch (e) { + console.error('ERR: Unable to parse .injectrrc file'); + } + } catch (e) {} +})(); module.exports = function (file, mocks, context) { var script; @@ -11,7 +34,7 @@ module.exports = function (file, mocks, context) { context = context || {}; file = path.join(path.dirname(module.parent.filename), file); cache[file] = cache[file] || module.exports.onload(file, - fs.readFileSync(file, 'utf8')); + fs.readFileSync(file, encoding)); script = vm.createScript(cache[file], file); context.require = function (a) { if (mocks[a]) { @@ -35,6 +58,11 @@ module.exports.onload = function (file, content) { return require('coffee-script').compile(content, { filename : file }); + } else if (options.babel && file.match(/\.js(x)?$/)) { + return require('babel-core').transform( + content, + options.babelOptions || {} + ).code; } return content; };