Skip to content

Commit

Permalink
Cleanup + add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
devongovett committed Jul 21, 2018
1 parent 49f7ad0 commit 2daf2e2
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 13 deletions.
32 changes: 19 additions & 13 deletions src/Resolver.js
Expand Up @@ -228,16 +228,11 @@ class Resolver {
try {
pkg = await this.readPackage(dir);

let fileList = this.listPossibleFiles(pkg);
for (let file of fileList) {
if (typeof file != 'string') {
continue;
}
if (file == '.' || file == './') {
file = 'index';
}
file = path.resolve(pkg.pkgdir, file);
// Get a list of possible package entry points.
let entries = this.getPackageEntries(pkg);

for (let file of entries) {
// First try loading package.main as a file, then try as a directory.
const res =
(await this.loadAsFile(file, extensions, pkg)) ||
(await this.loadDirectory(file, extensions, pkg));
Expand Down Expand Up @@ -278,10 +273,12 @@ class Resolver {
return pkg;
}

listPossibleFiles(pkg) {
let {browser} = pkg;
getBrowserField(pkg) {
let target = this.options.target || 'browser';
return target === 'browser' ? pkg.browser : null;
}

getPackageMain(pkg) {
getPackageEntries(pkg) {
let browser = this.getBrowserField(pkg);
if (browser && typeof browser === 'object' && browser[pkg.name]) {
browser = browser[pkg.name];
Expand All @@ -290,7 +287,16 @@ class Resolver {
// libraries like d3.js specifies node.js specific files in the "main" which breaks the build
// we use the "browser" or "module" field to get the full dependency tree if available.
// If this is a linked module with a `source` field, use that as the entry point.
return [pkg.source, browser, pkg.module, pkg.main];
return [pkg.source, browser, pkg.module, pkg.main]
.filter(entry => typeof entry === 'string')
.map(main => {
// Default to index file if no main field find
if (!main || main === '.' || main === './') {
main = 'index';
}

return path.resolve(pkg.pkgdir, main);
});
}

async loadAsFile(file, extensions, pkg) {
Expand Down
Empty file.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions test/resolver.js
Expand Up @@ -176,6 +176,18 @@ describe('resolver', function() {
assert.equal(resolved.pkg.name, 'package-browser');
});

it('should fall back to package.main when package.module does not exist', async function() {
let resolved = await resolver.resolve(
'package-module-fallback',
path.join(rootDir, 'foo.js')
);
assert.equal(
resolved.path,
path.join(rootDir, 'node_modules', 'package-module-fallback', 'main.js')
);
assert.equal(resolved.pkg.name, 'package-module-fallback');
});

it('should not resolve a node_modules package.browser main field with --target=node', async function() {
let resolver = new Resolver({
rootDir,
Expand Down

0 comments on commit 2daf2e2

Please sign in to comment.