Skip to content

Commit

Permalink
add define.default
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanpenner committed Aug 15, 2018
1 parent 27b4098 commit d0cf32c
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ require('foo/bar/baz') // => 'hi';
require('foo') === require('foo/bar/baz');
```



### `define.default('old/path', 'new-name')`

`define.default` is short-hand for `export { default } from 'foo';`

```js
define('foo', [], () => 'hi');
define.default('foo', 'foo/bar/baz');

require('foo/bar/baz') // => 'hi';
require('foo') === require('foo/bar/baz');
```

### `require('require')`

When within a module, one can require `require`. This provides a `require` scoped to the current module. Enabling dynamic, relatively path requires.
Expand Down
13 changes: 12 additions & 1 deletion lib/loader/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,9 @@ var loader, define, requireModule, require, requirejs;
// we don't support all of AMD
// define.amd = {};

function Alias(id) {
function Alias(id, prop) {
this.id = id;
this.prop = prop;
}

define.alias = function(id, target) {
Expand All @@ -277,6 +278,16 @@ var loader, define, requireModule, require, requirejs;
return new Alias(id);
};

define.default = function(id, target) {
define(id, ['exports', target], function(exports, targetExports) {
Object.defineProperty(exports, 'default', {
get: function() {
return targetExports.default;
}
});
});
};

function missingModule(id, referrer) {
throw new Error('Could not find module `' + id + '` imported from `' + referrer + '`');
}
Expand Down
37 changes: 37 additions & 0 deletions tests/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,43 @@ test('alias entries share same module instance', function() {
});
});

test('define.default with default and other exports', function() {
var count = 0;
define.default('to', 'from');
define('from', ['exports'], function(exports) {
count++;

exports.default = 'YUP';
exports.other = 'NOPE';
});

equal(count, 0);
var result = require('to');
equal(count, 1);
equal(result.default, 'YUP');
deepEqual(require('from'), {
default: 'YUP',
other: 'NOPE',
});

equal(count, 1, 'second require should use existing instance');

var stats = statsForMonitor('loaderjs', tree);

deepEqual(stats, {
define: 2,
exports: 2,
findDeps: 2,
findModule: 3,
modules: 2,
pendingQueueLength: 2,
reify: 2,
require: 2,
resolve: 1,
resolveRelative: 0
});
});

test('alias with 2 arguments entries share same module instance', function() {
var count = 0;
define.alias('foo/index', 'bar');
Expand Down

0 comments on commit d0cf32c

Please sign in to comment.