| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | /** @typedef {import("./Resolver")} Resolver */
|
|---|
| 9 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
|---|
| 10 | /** @typedef {string | string[] | false} Alias */
|
|---|
| 11 | /** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */
|
|---|
| 12 |
|
|---|
| 13 | const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils");
|
|---|
| 14 |
|
|---|
| 15 | /**
|
|---|
| 16 | * When `alias` is given as an array, the targets are tried in priority
|
|---|
| 17 | * order and the first matching one wins. Tried-and-failed higher-priority
|
|---|
| 18 | * targets are recorded on `resolveContext.missingDependencies` (via the
|
|---|
| 19 | * downstream `FileExistsPlugin`) so that a consumer's watcher can
|
|---|
| 20 | * invalidate the resolve once one of them appears. The winning target is
|
|---|
| 21 | * recorded on `resolveContext.fileDependencies`; its removal triggers
|
|---|
| 22 | * re-resolution, at which point the fallback target is returned.
|
|---|
| 23 | *
|
|---|
| 24 | * Callers that cache successful resolves (e.g. webpack's `unsafeCache`)
|
|---|
| 25 | * are responsible for invalidating those entries when the tracked
|
|---|
| 26 | * dependencies change -- otherwise a stale path may survive across
|
|---|
| 27 | * rebuilds even though this plugin itself would return the correct
|
|---|
| 28 | * fallback on a fresh resolve.
|
|---|
| 29 | */
|
|---|
| 30 | module.exports = class AliasPlugin {
|
|---|
| 31 | /**
|
|---|
| 32 | * @param {string | ResolveStepHook} source source
|
|---|
| 33 | * @param {AliasOption | AliasOption[]} options options
|
|---|
| 34 | * @param {string | ResolveStepHook} target target
|
|---|
| 35 | */
|
|---|
| 36 | constructor(source, options, target) {
|
|---|
| 37 | this.source = source;
|
|---|
| 38 | this.options = Array.isArray(options) ? options : [options];
|
|---|
| 39 | this.target = target;
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | /**
|
|---|
| 43 | * @param {Resolver} resolver the resolver
|
|---|
| 44 | * @returns {void}
|
|---|
| 45 | */
|
|---|
| 46 | apply(resolver) {
|
|---|
| 47 | const target = resolver.ensureHook(this.target);
|
|---|
| 48 | const compiled = compileAliasOptions(resolver, this.options);
|
|---|
| 49 |
|
|---|
| 50 | resolver
|
|---|
| 51 | .getHook(this.source)
|
|---|
| 52 | .tapAsync("AliasPlugin", (request, resolveContext, callback) => {
|
|---|
| 53 | aliasResolveHandler(
|
|---|
| 54 | resolver,
|
|---|
| 55 | compiled,
|
|---|
| 56 | target,
|
|---|
| 57 | request,
|
|---|
| 58 | resolveContext,
|
|---|
| 59 | callback,
|
|---|
| 60 | );
|
|---|
| 61 | });
|
|---|
| 62 | }
|
|---|
| 63 | };
|
|---|