Skip to content

Commit

Permalink
Fix invalid string extension replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanmourtada committed Feb 15, 2017
1 parent af62bfa commit d6b7c53
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/match-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type MatchPath = (
* @param paths The paths specified in tsconfig.
*/
export function createMatchPath(
absoluteBaseUrl:string,
absoluteBaseUrl: string,
paths: { [key: string]: Array<string> }): MatchPath {

// Resolve all paths to absolute form once here, this saves time on each request later
Expand Down Expand Up @@ -94,7 +94,9 @@ function tryResolve(physicalPath: string,

if (packageJson && packageJson.main && fileExists(path.join(physicalPath, packageJson.main))) {
const file = path.join(physicalPath, packageJson.main);
return file.replace(path.extname(file), "");
const fileExtension = path.extname(file).replace(/^\./, "");
const fileExtensionRegex = new RegExp(`\.${fileExtension}$`);
return fileExtension ? file.replace(fileExtensionRegex, "") : file;
}

const indexPath = path.join(physicalPath, "/index");
Expand Down
24 changes: 24 additions & 0 deletions tests/match-path-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,30 @@ describe('find-path', function () {
assert.equal(result, "/root/location/mylib/kalle");
});

it('should resolve from main field in package.json and correctly remove file extension', () => {

const matchPath = createMatchPath("/root/", { "lib/*": ["location/*"] });
const result = matchPath(
"/root/subfolder/file.js",
"lib/mylib.js",
(_: string) => ({ main: "./kalle.js" }),
(name: string) => name === "/root/location/mylib.js/kalle.js",
[".ts", ".js"]
);

// Make sure we escape the "."
const result2 = matchPath(
"/root/subfolder/file.js",
"lib/mylibjs",
(_: string) => ({ main: "./kallejs" }),
(name: string) => name === "/root/location/mylibjs/kallejs",
[".ts", ".js"]
);
console.log(result2);
assert.equal(result, "/root/location/mylib.js/kalle");
assert.equal(result2, "/root/location/mylibjs/kallejs");
});

it('should not locate path that does not match', () => {

const matchPath = createMatchPath("/root/", { "lib/*": ["location/*"] });
Expand Down

0 comments on commit d6b7c53

Please sign in to comment.