Skip to content

Commit

Permalink
feat: support exports in package.json (#11961)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Feb 10, 2022
1 parent a5f58b5 commit b9e3a55
Show file tree
Hide file tree
Showing 18 changed files with 158 additions and 54 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
- `[@jest/expect-utils]` New module exporting utils for `expect` ([#12323](https://github.com/facebook/jest/pull/12323))
- `[jest-jasmine2, jest-runtime]` [**BREAKING**] Use `Symbol` to pass `jest.setTimeout` value instead of `jasmine` specific logic ([#12124](https://github.com/facebook/jest/pull/12124))
- `[jest-jasmine2, jest-types]` [**BREAKING**] Move all `jasmine` specific types from `@jest/types` to its own package ([#12125](https://github.com/facebook/jest/pull/12125))
- `[jest-resolver]` [**BREAKING**] Add support for `package.json` `exports` ([11961](https://github.com/facebook/jest/pull/11961))
- `[jest-snapshot]` [**BREAKING**] Migrate to ESM ([#12342](https://github.com/facebook/jest/pull/12342))
- `[jest-worker]` [**BREAKING**] Allow only absolute `workerPath` ([#12343](https://github.com/facebook/jest/pull/12343))

Expand Down
2 changes: 1 addition & 1 deletion examples/angular/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
moduleFileExtensions: ['ts', 'html', 'js', 'json'],
setupFilesAfterEnv: ['<rootDir>/setupJest.js'],
testEnvironment: 'jsdom',
testEnvironment: '<rootDir>/test-env.js',
transform: {
'\\.[tj]s$': ['babel-jest', {configFile: require.resolve('./.babelrc')}],
},
Expand Down
13 changes: 13 additions & 0 deletions examples/angular/test-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

const {
TestEnvironment: JSDOMTestEnvironment,
} = require('jest-environment-jsdom');

module.exports = class AngularEnv extends JSDOMTestEnvironment {
exportConditions() {
// we need to include `node` as `rxjs` defines `node`, `es2015`, `default`, not `browser` or `require`
// https://github.com/ReactiveX/rxjs/pull/6821
return super.exportConditions().concat('node');
}
};
Empty file.
Empty file.
Empty file.
Empty file.

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

Empty file.

This file was deleted.

This file was deleted.

64 changes: 59 additions & 5 deletions packages/jest-resolve/src/__tests__/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,24 +160,78 @@ describe('findNodeModule', () => {
});

test('resolves with import', () => {
const result = Resolver.findNodeModule('import', {
const result = Resolver.findNodeModule('exports', {
basedir: conditionsRoot,
conditions: ['import'],
});

expect(result).toEqual(
path.resolve(conditionsRoot, './node_modules/import/file.js'),
path.resolve(conditionsRoot, './node_modules/exports/import.js'),
);
});

test('resolves with require', () => {
const result = Resolver.findNodeModule('require', {
const result = Resolver.findNodeModule('exports', {
basedir: conditionsRoot,
conditions: ['require'],
});

expect(result).toEqual(
path.resolve(conditionsRoot, './node_modules/require/file.js'),
path.resolve(conditionsRoot, './node_modules/exports/require.js'),
);
});

test('gets default when nothing is passed', () => {
const result = Resolver.findNodeModule('exports', {
basedir: conditionsRoot,
conditions: [],
});

expect(result).toEqual(
path.resolve(conditionsRoot, './node_modules/exports/default.js'),
);
});

test('respects order in package.json, not conditions', () => {
const resultImport = Resolver.findNodeModule('exports', {
basedir: conditionsRoot,
conditions: ['import', 'require'],
});
const resultRequire = Resolver.findNodeModule('exports', {
basedir: conditionsRoot,
conditions: ['require', 'import'],
});

expect(resultImport).toEqual(resultRequire);
});

test('supports nested paths', () => {
const result = Resolver.findNodeModule('exports/nested', {
basedir: conditionsRoot,
conditions: [],
});

expect(result).toEqual(
path.resolve(conditionsRoot, './node_modules/exports/nestedDefault.js'),
);
});

test('supports nested conditions', () => {
const resultRequire = Resolver.findNodeModule('exports/deeplyNested', {
basedir: conditionsRoot,
conditions: ['require'],
});
const resultDefault = Resolver.findNodeModule('exports/deeplyNested', {
basedir: conditionsRoot,
conditions: [],
});

expect(resultRequire).toEqual(
path.resolve(conditionsRoot, './node_modules/exports/nestedRequire.js'),
);

expect(resultDefault).toEqual(
path.resolve(conditionsRoot, './node_modules/exports/nestedDefault.js'),
);
});
});
Expand Down Expand Up @@ -251,8 +305,8 @@ describe('resolveModule', () => {
const src = require.resolve('../');
const resolved = resolver.resolveModule(src, 'mockJsDependency', {
paths: [
path.resolve(__dirname, '../../src/__tests__'),
path.resolve(__dirname, '../../src/__mocks__'),
path.resolve(__dirname, '../../src/__tests__'),
],
});
expect(resolved).toBe(require.resolve('../__mocks__/mockJsDependency.js'));
Expand Down
82 changes: 52 additions & 30 deletions packages/jest-resolve/src/defaultResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
* LICENSE file in the root directory of this source tree.
*/

import {resolve} from 'path';
import {isAbsolute} from 'path';
import pnpResolver from 'jest-pnp-resolver';
import {sync as resolveSync} from 'resolve';
import {
Options as ResolveExportsOptions,
resolve as resolveExports,
} from 'resolve.exports';
import slash = require('slash');
import type {Config} from '@jest/types';
import {
PkgJson,
Expand Down Expand Up @@ -59,10 +60,8 @@ export default function defaultResolver(
...options,
isDirectory,
isFile,
packageFilter: createPackageFilter(
options.conditions,
options.packageFilter,
),
packageFilter: createPackageFilter(path, options.packageFilter),
pathFilter: createPathFilter(path, options.conditions, options.pathFilter),
preserveSymlinks: false,
readPackageSync,
realpathSync,
Expand All @@ -82,45 +81,68 @@ function readPackageSync(_: unknown, file: Config.Path): PkgJson {
}

function createPackageFilter(
conditions?: Array<string>,
originalPath: Config.Path,
userFilter?: ResolverOptions['packageFilter'],
): ResolverOptions['packageFilter'] {
function attemptExportsFallback(pkg: PkgJson) {
const options: ResolveExportsOptions = conditions
? {conditions, unsafe: true}
: // no conditions were passed - let's assume this is Jest internal and it should be `require`
{browser: false, require: true};

try {
return resolveExports(pkg, '.', options);
} catch {
return undefined;
}
if (shouldIgnoreRequestForExports(originalPath)) {
return userFilter;
}

return function packageFilter(pkg, packageDir) {
return function packageFilter(pkg, ...rest) {
let filteredPkg = pkg;

if (userFilter) {
filteredPkg = userFilter(filteredPkg, packageDir);
}

if (filteredPkg.main != null) {
return filteredPkg;
filteredPkg = userFilter(filteredPkg, ...rest);
}

const indexInRoot = resolve(packageDir, './index.js');

// if the module contains an `index.js` file in root, `resolve` will request
// that if there is no `main`. Since we don't wanna break that, add this
// check
if (isFile(indexInRoot)) {
if (filteredPkg.exports == null) {
return filteredPkg;
}

return {
...filteredPkg,
main: attemptExportsFallback(filteredPkg),
// remove `main` so `resolve` doesn't look at it and confuse the `.`
// loading in `pathFilter`
main: undefined,
};
};
}

function createPathFilter(
originalPath: Config.Path,
conditions?: Array<string>,
userFilter?: ResolverOptions['pathFilter'],
): ResolverOptions['pathFilter'] {
if (shouldIgnoreRequestForExports(originalPath)) {
return userFilter;
}

const options: ResolveExportsOptions = conditions
? {conditions, unsafe: true}
: // no conditions were passed - let's assume this is Jest internal and it should be `require`
{browser: false, require: true};

return function pathFilter(pkg, path, relativePath, ...rest) {
let pathToUse = relativePath;

if (userFilter) {
pathToUse = userFilter(pkg, path, relativePath, ...rest);
}

if (pkg.exports == null) {
return pathToUse;
}

// this `index` thing can backfire, but `resolve` adds it: https://github.com/browserify/resolve/blob/f1b51848ecb7f56f77bfb823511d032489a13eab/lib/sync.js#L192
const isRootRequire =
pathToUse === 'index' && !originalPath.endsWith('/index');

const newPath = isRootRequire ? '.' : slash(pathToUse);

return resolveExports(pkg, newPath, options) || pathToUse;
};
}

// if it's a relative import or an absolute path, exports are ignored
const shouldIgnoreRequestForExports = (path: Config.Path) =>
path.startsWith('.') || isAbsolute(path);
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "NODE_PATH_dir",
"version": "1.0.0",
"dependencies": {
}
}
6 changes: 6 additions & 0 deletions packages/jest-runtime/src/__tests__/test_root/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "test_root",
"version": "1.0.0",
"dependencies": {
}
}
10 changes: 4 additions & 6 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ export default class Runtime {
this._virtualMocks,
from,
moduleName,
isInternal ? undefined : {conditions: this.cjsConditions},
{conditions: this.cjsConditions},
);
let modulePath: string | undefined;

Expand Down Expand Up @@ -782,11 +782,9 @@ export default class Runtime {
}

if (!modulePath) {
modulePath = this._resolveModule(
from,
moduleName,
isInternal ? undefined : {conditions: this.cjsConditions},
);
modulePath = this._resolveModule(from, moduleName, {
conditions: this.cjsConditions,
});
}

if (this.unstable_shouldLoadAsEsm(modulePath)) {
Expand Down

0 comments on commit b9e3a55

Please sign in to comment.