Skip to content
Open
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
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 30 additions & 2 deletions lib/injectr.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,38 @@
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;
mocks = mocks || {};
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]) {
Expand All @@ -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;
};