Skip to content

Commit

Permalink
Merge pull request ember-cli#62 from jschilli/add-annotator
Browse files Browse the repository at this point in the history
Allow utilities to wrap/morph callbacks before loader finalizes them
  • Loading branch information
stefanpenner committed Jan 7, 2016
2 parents aa9e24c + 668aad9 commit 5f05ffe
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ Note: To be able to take advantage of alternate `define` method name, you will a
build tooling generates using the alternate. An example of this is done in the [emberjs-build](https://github.com/emberjs/emberjs-build)
project in the [babel-enifed-module-formatter plugin](https://github.com/emberjs/emberjs-build/blob/v0.4.2/lib/utils/babel-enifed-module-formatter.js).

## wrapModules

It is possible to hook loader to augment or transform the loaded code. `wrapModules` is an optional method on the loader that is called as each module is originally loaded. `wrapModules` must be a function of the form `wrapModules(name, callback)`. The `callback` is the original AMD callback. The return value of `wrapModules` is then used in subsequent requests for `name`

This functionality is useful for instrumenting code, for instance in code coverage libraries.

```
loader.wrapModules = function(name, callback) {
if (shouldTransform(name) {
return myTransformer(name, callback);
}
}
return callback;
};
```

## Tests

To run the test you'll need to have
Expand Down
3 changes: 3 additions & 0 deletions loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ var global = this;
if (this.finalized) {
return this.module.exports;
} else {
if (loader.wrapModules) {
this.callback = loader.wrapModules(this.name, this.callback);
}
var result = this.callback.apply(this, reifiedDeps);
if (!(this.hasExportsAsDep && result === undefined)) {
this.module.exports = result;
Expand Down
16 changes: 16 additions & 0 deletions tests/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,19 @@ test('alias chaining with relative deps works', function() {
equal(require('foo/index'), 'I AM foo/index: I AM baz');
equal(require('bar'), 'I AM foo/index: I AM baz');
});

test('wrapModules is called when present', function() {
var fooCalled = 0;
var annotatorCalled = 0;
loader.wrapModules = function(name, callback) {
annotatorCalled++;
return callback;
};
define('foo', [], function() {
fooCalled++;
});

equal(annotatorCalled, 0);
require('foo');
equal(annotatorCalled, 1);
});

0 comments on commit 5f05ffe

Please sign in to comment.