Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(alias) Breaking feature: built-in resolving algorithm is replaced in favor of Rollup's this.resolve() #34

Merged
merged 16 commits into from
Dec 16, 2019
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 9 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,7 @@ module.exports = {
dir: 'output',
format: 'cjs'
},
plugins: [alias({ resolve: ['.jsx', '.js'] })]
plugins: [alias()]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would be good to include example usage here

};
```

Expand All @@ -65,7 +67,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 +100,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 +120,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
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'];
Acionyx marked this conversation as resolved.
Show resolved Hide resolved
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;
});
}
};
}
Loading