Skip to content

Commit

Permalink
feat(node-resolve): support package entry points
Browse files Browse the repository at this point in the history
  • Loading branch information
LarsDenBakker committed Aug 13, 2020
1 parent e4d21ba commit 21f76b7
Show file tree
Hide file tree
Showing 55 changed files with 435 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
.eslintrc.js
.eslintrc.js
15 changes: 11 additions & 4 deletions packages/node-resolve/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,23 @@ export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
format: 'cjs',
},
plugins: [nodeResolve()]
plugins: [nodeResolve()],
};
```

Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).

## Options

### `exportConditions`

Type: `Array[...String]`<br>
Default: `['module', 'default']`

Conditions used to select exports defined using node js [package exports](https://nodejs.org/api/esm.html#esm_packages). Conditions are evaluated left to right, returning the first match that is found. Setting this property overwrites the default values.

### `browser`

Type: `Boolean`<br>
Expand Down Expand Up @@ -164,9 +171,9 @@ export default {
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyModule'
name: 'MyModule',
},
plugins: [resolve(), commonjs()]
plugins: [resolve(), commonjs()],
};
```

Expand Down
13 changes: 10 additions & 3 deletions packages/node-resolve/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
const builtins = new Set(builtinList);
const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
const nullFn = () => null;
const deepFreeze = object => {
const deepFreeze = (object) => {
Object.freeze(object);

for (const value of Object.values(object)) {
Expand All @@ -30,6 +30,7 @@ const deepFreeze = object => {
return object;
};
const defaults = {
exportConditions: ['module', 'default'],
customResolveOptions: {},
dedupe: [],
// It's important that .mjs is listed before .js so that Rollup will interpret npm modules
Expand All @@ -41,7 +42,7 @@ export const DEFAULTS = deepFreeze(deepMerge({}, defaults));

export function nodeResolve(opts = {}) {
const options = Object.assign({}, defaults, opts);
const { customResolveOptions, extensions, jail } = options;
const { exportConditions, customResolveOptions, extensions, jail } = options;
const warnings = [];
const packageInfoCache = new Map();
const idToPackageInfo = new Map();
Expand Down Expand Up @@ -220,7 +221,13 @@ export function nodeResolve(opts = {}) {
resolveOptions = Object.assign(resolveOptions, customResolveOptions);

try {
let resolved = await resolveImportSpecifiers(importSpecifierList, resolveOptions);
const warn = (...args) => this.warn(...args);
let resolved = await resolveImportSpecifiers(
importSpecifierList,
resolveOptions,
exportConditions,
warn
);

if (resolved && packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
Expand Down
121 changes: 121 additions & 0 deletions packages/node-resolve/src/resolveId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';

import resolve from 'resolve';

import { getPackageName } from './util';

const resolveImportPath = promisify(resolve);
const readFile = promisify(fs.readFile);

const pathNotFoundError = (subPath, pkgPath) =>
new Error(`Package subpath '${subPath}' is not defined by "exports" in ${pkgPath}`);

function mapSubPath(pkgJsonPath, subPath, value) {
if (typeof value === 'string') {
// mapping is a string, for example { "./foo": "./dist/foo.js" }
return value;
}

if (Array.isArray(value)) {
// mapping is an array with fallbacks, for example { "./foo": ["foo:bar", "./dist/foo.js"] }
return value.find((v) => v.startsWith('./'));
}

throw pathNotFoundError(subPath, pkgJsonPath);
}

function findEntrypoint(pkgJsonPath, subPath, exportMap, conditions) {
if (typeof exportMap !== 'object') {
return mapSubPath(pkgJsonPath, subPath, exportMap);
}

// iterate conditions recursively, find the first that matches all conditions
for (const [condition, subExportMap] of Object.entries(exportMap)) {
if (conditions.includes(condition)) {
const mappedSubPath = findEntrypoint(pkgJsonPath, subPath, subExportMap, conditions);
if (mappedSubPath) {
return mappedSubPath;
}
}
}
throw pathNotFoundError(subPath, pkgJsonPath);
}

export function findEntrypointTopLevel(pkgJsonPath, subPath, exportMap, conditions) {
if (typeof exportMap !== 'object') {
// the export map shorthand, for example { exports: "./index.js" }
if (subPath !== '.') {
// shorthand only supports a main entrypoint
throw pathNotFoundError(subPath, pkgJsonPath);
}
return mapSubPath(pkgJsonPath, subPath, exportMap);
}

// export map is an object, the top level can be either conditions or sub path mappings
const keys = Object.keys(exportMap);
const isConditions = keys.every((k) => !k.startsWith('.'));
const isMappings = keys.every((k) => k.startsWith('.'));

if (!isConditions && !isMappings) {
throw new Error(
`Invalid package config ${pkgJsonPath}, "exports" cannot contain some keys starting with '.'` +
' and some not. The exports object must either be an object of package subpath keys or an object of main entry' +
' condition name keys only.'
);
}

let exportMapForSubPath;

if (isConditions) {
// top level is conditions, for example { "import": ..., "require": ..., "module": ... }
if (subPath !== '.') {
// package with top level conditions means it only supports a main entrypoint
throw pathNotFoundError(subPath, pkgJsonPath);
}
exportMapForSubPath = exportMap;
} else {
// top level is sub path mappings, for example { ".": ..., "./foo": ..., "./bar": ... }
if (!(subPath in exportMap)) {
throw pathNotFoundError(subPath, pkgJsonPath);
}
exportMapForSubPath = exportMap[subPath];
}

return findEntrypoint(pkgJsonPath, subPath, exportMapForSubPath, conditions);
}

export default async function resolveId(importPath, options, exportConditions, warn) {
const pkgName = getPackageName(importPath);
if (pkgName) {
let pkgJsonPath;
let pkgJson;
try {
pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, options);
pkgJson = JSON.parse(await readFile(pkgJsonPath, 'utf-8'));
} catch (_) {
// if there is no package.json we defer to regular resolve behavior
}

if (pkgJsonPath && pkgJson && pkgJson.exports) {
try {
const packageSubPath =
pkgName === importPath ? '.' : `.${importPath.substring(pkgName.length)}`;
const mappedSubPath = findEntrypointTopLevel(
pkgJsonPath,
packageSubPath,
pkgJson.exports,
exportConditions
);
const pkgDir = path.dirname(pkgJsonPath);
return path.join(pkgDir, mappedSubPath);
} catch (error) {
warn(error);
return null;
}
}
}

return resolveImportPath(importPath, options);
}
24 changes: 14 additions & 10 deletions packages/node-resolve/src/util.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { dirname, extname, resolve } from 'path';
import { promisify } from 'util';

import { createFilter } from '@rollup/pluginutils';

import resolveModule from 'resolve';
import resolveId from './resolveId';

import { realpathSync } from './fs';

const resolveId = promisify(resolveModule);

// returns the imported package name for bare module imports
export function getPackageName(id) {
if (id.startsWith('.') || id.startsWith('/')) {
Expand Down Expand Up @@ -161,7 +158,12 @@ export function normalizeInput(input) {

// Resolve module specifiers in order. Promise resolves to the first module that resolves
// successfully, or the error that resulted from the last attempted module resolution.
export function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
export function resolveImportSpecifiers(
importSpecifierList,
resolveOptions,
exportConditions,
warn
) {
let promise = Promise.resolve();

for (let i = 0; i < importSpecifierList.length; i++) {
Expand All @@ -171,12 +173,14 @@ export function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
return value;
}

return resolveId(importSpecifierList[i], resolveOptions).then((result) => {
if (!resolveOptions.preserveSymlinks) {
result = realpathSync(result);
return resolveId(importSpecifierList[i], resolveOptions, exportConditions, warn).then(
(result) => {
if (!resolveOptions.preserveSymlinks) {
result = realpathSync(result);
}
return result;
}
return result;
});
);
});

if (i < importSpecifierList.length - 1) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import main from 'exports-mappings-and-conditions';
import foo from 'exports-mappings-and-conditions/foo';
import bar from 'exports-mappings-and-conditions/bar';

export default { main, foo, bar };
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import main from 'exports-nested-conditions';

export default main;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import bar from 'exports-non-existing-subpath/bar';

export default bar;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import bar from 'exports-top-level-mappings/bar';

export default bar;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import exportsMapEntry from 'exports-shorthand';

export default exportsMapEntry;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import exportsMapEntry from 'exports-shorthand/foo';

export default exportsMapEntry;
3 changes: 3 additions & 0 deletions packages/node-resolve/test/fixtures/exports-shorthand.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import exportsMapEntry from 'exports-shorthand';

export default exportsMapEntry;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import main from 'exports-top-level-conditions';

export default main;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import main from 'exports-top-level-mappings';
import foo from 'exports-top-level-mappings/foo';

export default { main, foo };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading

0 comments on commit 21f76b7

Please sign in to comment.