Skip to content

Commit

Permalink
Merge pull request #337 from webpack/fix/issue-334
Browse files Browse the repository at this point in the history
fix hash aliases
  • Loading branch information
sokra authored Apr 12, 2022
2 parents 23c3e7c + 5d90d19 commit 82f1759
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
21 changes: 16 additions & 5 deletions lib/AliasPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"use strict";

const forEachBail = require("./forEachBail");
const { PathType, getType } = require("./util/path");

/** @typedef {import("./Resolver")} Resolver */
/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
Expand All @@ -30,6 +31,18 @@ module.exports = class AliasPlugin {
*/
apply(resolver) {
const target = resolver.ensureHook(this.target);
const getAbsolutePathWithSlashEnding = maybeAbsolutePath => {
const type = getType(maybeAbsolutePath);
if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) {
return resolver.join(maybeAbsolutePath, "_").slice(0, -1);
}
return null;
};
const isSubPath = (path, maybeSubPath) => {
const absolutePath = getAbsolutePathWithSlashEnding(maybeSubPath);
if (!absolutePath) return false;
return path.startsWith(absolutePath);
};
resolver
.getHook(this.source)
.tapAsync("AliasPlugin", (request, resolveContext, callback) => {
Expand All @@ -42,11 +55,9 @@ module.exports = class AliasPlugin {
if (
innerRequest === item.name ||
(!item.onlyModule &&
innerRequest.startsWith(
request.request
? `${item.name}/`
: resolver.join(item.name, "_").slice(0, -1)
))
(request.request
? innerRequest.startsWith(`${item.name}/`)
: isSubPath(innerRequest, item.name)))
) {
const remainingRequest = innerRequest.substr(item.name.length);
const resolveWithAlias = (alias, callback) => {
Expand Down
11 changes: 11 additions & 0 deletions test/alias.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ describe("alias", function () {
recursive: "recursive/dir",
"/d/dir": "/c/dir",
"/d/index.js": "/c/index",
// alias configuration should work
"#": "/c/dir",
"@": "/c/dir",
ignored: false
},
modules: "/",
Expand All @@ -61,6 +64,14 @@ describe("alias", function () {
.resolveSync({}, "/", "aliasA/dir/index")
.should.be.eql("/a/dir/index");
});
it('should resolve "#" alias', () => {
resolver.resolveSync({}, "/", "#").should.be.eql("/c/dir/index");
resolver.resolveSync({}, "/", "#/index").should.be.eql("/c/dir/index");
});
it('should resolve "@" alias', () => {
resolver.resolveSync({}, "/", "@").should.be.eql("/c/dir/index");
resolver.resolveSync({}, "/", "@/index").should.be.eql("/c/dir/index");
});
it("should resolve an ignore module", () => {
resolver.resolveSync({}, "/", "ignored").should.be.eql(false);
});
Expand Down

0 comments on commit 82f1759

Please sign in to comment.