Skip to content

Commit

Permalink
feat(alias): built-in resolving algorithm is replaced in favor of Rol…
Browse files Browse the repository at this point in the history
…lup's `this.resolve()` (#34)

## Breaking Change 

* ignore Intellij IDEA dir

* updated pnpm-lock.yaml

According to pnpm actual version and included packages

* @rollup/plugin-alias: customResolver option

Allow to use customResolver instead of built-in resolving algorithm in

* @rollup/plugin-alias: updated readme

customResolver option

* (alias) updated README

customResolver description

* docs: rework custom resolver options and section

* (alias) customResolver bugfix

* feat(alias): Built-in resolving algorithm is removed

@@ BREAKING @@
And replaced by Rollup's context function `this.resolve()`

* (alias) Fixes according to PR discussion

Tests: every test is done by invoking Rollup instance;
Plugin: fixed according to linter warnings;
Readme: updated.

* (alias) fixes according to review
  • Loading branch information
Acionyx authored and shellscape committed Dec 16, 2019
1 parent f9dac38 commit 46c75f4
Show file tree
Hide file tree
Showing 7 changed files with 460 additions and 1,092 deletions.
30 changes: 16 additions & 14 deletions packages/alias/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Using npm:

```console
npm install @rollup/plugin-alias --save-dev
# or
yarn add -D @rollup/plugin-alias
```

## Usage
Expand All @@ -52,7 +54,14 @@ module.exports = {
dir: 'output',
format: 'cjs'
},
plugins: [alias({ resolve: ['.jsx', '.js'] })]
plugins: [
alias({
entries: [
{ find: 'utils', replacement: '../../../utils' },
{ find: 'batman-1.0.0', replacement: './joker-1.5.0' }
]
})
]
};
```

Expand All @@ -65,7 +74,7 @@ Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#comma
Type: `Function | Object`<br>
Default: `null`

Instructs the plugin to use an alternative resolving algorithm, rather than the built-in resolver. Please refer to the [Rollup documentation](https://rollupjs.org/guide/en/#hooks) for more information about the `resolveId` hook. For a detailed example, see: [Custom Resolvers](#custom-resolvers).
Instructs the plugin to use an alternative resolving algorithm, rather than the Rollup's resolver. Please refer to the [Rollup documentation](https://rollupjs.org/guide/en/#hooks) for more information about the `resolveId` hook. For a detailed example, see: [Custom Resolvers](#custom-resolvers).

### `entries`

Expand Down Expand Up @@ -98,17 +107,6 @@ entries: [
];
```

### `resolve`

Type: `Array[String]`<br>
Default: `['.js']`

Specifies an array of file extensions to use when attempting to resolve an `import` (or `require`). The extensions will be tried in the order they are specified. By default, this option is configured to resolve only files that have the `.js` extension. For example; to resolve both `JSX` and `JS` files:

```js
alias({ resolve: ['.jsx', '.js'] });
```

## Regular Expression Aliases

Regular Expressions can be used to search in a more distinct and complex manner. e.g. To perform partial replacements via sub-pattern matching.
Expand All @@ -129,9 +127,13 @@ To replace extensions with another, a pattern like the following might be used:

This would replace the file extension for all imports ending with `.js` to `.alias`.

## Resolving algorithm

This plugin uses resolver plugins specified for Rollup and eventually Rollup default algorithm. If you rely on Node specific features, you probably want [rollup-plugin-node-resolve](https://www.npmjs.com/package/rollup-plugin-node-resolve) in your setup.

## Custom Resolvers

The `customResolver` option can be leveraged to provide separate module resolution for an invidudual alias.
The `customResolver` option can be leveraged to provide separate module resolution for an individual alias.

Example:

Expand Down
3 changes: 2 additions & 1 deletion packages/alias/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@
},
"devDependencies": {
"del-cli": "^3.0.0",
"rollup": "^1.20.0"
"rollup": "^1.20.0",
"rollup-plugin-node-resolve": "^5.2.0"
},
"ava": {
"files": [
Expand Down
53 changes: 9 additions & 44 deletions packages/alias/src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import fs from 'fs';
import { platform } from 'os';
import path, { posix } from 'path';

import slash from 'slash';

Expand All @@ -23,15 +21,6 @@ const matches = (pattern, importee) => {
const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';
return importeeStartsWithKey && importeeHasSlashAfterKey;
};
const endsWith = (needle, haystack) => haystack.slice(-needle.length) === needle;
const isFilePath = (id) => /^\.?\//.test(id);
const exists = (uri) => {
try {
return fs.statSync(uri).isFile();
} catch (e) {
return false;
}
};

const normalizeId = (id) => {
if ((IS_WINDOWS && typeof id === 'string') || VOLUME.test(id)) {
Expand All @@ -55,7 +44,6 @@ const getEntries = ({ entries }) => {
};

export default function alias(options = {}) {
const resolve = Array.isArray(options.resolve) ? options.resolve : ['.js'];
const entries = getEntries(options);

// No aliases?
Expand All @@ -77,7 +65,9 @@ export default function alias(options = {}) {
return null;
}

let updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));
const updatedId = normalizeId(
importeeId.replace(matchedEntry.find, matchedEntry.replacement)
);

let customResolver = null;
if (typeof matchedEntry.customResolver === 'function') {
Expand All @@ -100,39 +90,14 @@ export default function alias(options = {}) {
return customResolver(updatedId, importerId);
}

if (isFilePath(updatedId)) {
const directory = posix.dirname(importerId);

// Resolve file names
const filePath = posix.resolve(directory, updatedId);
const match = resolve
.map((ext) => (endsWith(ext, filePath) ? filePath : `${filePath}${ext}`))
.find(exists);

if (match) {
updatedId = match;
// To keep the previous behaviour we simply return the file path
// with extension
} else if (endsWith('.js', filePath)) {
updatedId = filePath;
} else {
const indexFilePath = posix.resolve(directory, `${updatedId}/index`);
const defaultMatch = resolve.map((ext) => `${indexFilePath}${ext}`).find(exists);
if (defaultMatch) {
updatedId = defaultMatch;
} else {
updatedId = `${filePath}.js`;
}
return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {
let finalResult = resolved;
if (!finalResult) {
finalResult = { id: updatedId };
}
}

// if alias is windows absoulate path return resolved path or
// rollup on windows will throw:
// [TypeError: Cannot read property 'specifier' of undefined]
if (VOLUME.test(matchedEntry.replacement)) {
return path.resolve(updatedId);
}
return updatedId;
return finalResult;
});
}
};
}
1 change: 1 addition & 0 deletions packages/alias/test/fixtures/folder/deep/deep2/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default 1;
2 changes: 2 additions & 0 deletions packages/alias/test/fixtures/folder/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line import/no-unresolved, import/extensions
export { default } from 'superdeep';
Loading

0 comments on commit 46c75f4

Please sign in to comment.