fix(v2): redirect plugin: use siteConfig.trailingSlash (#4988)

This commit is contained in:
Sébastien Lorber 2021-06-16 19:04:28 +02:00 committed by GitHub
parent 80b6d9728e
commit b54ec72389
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 443 additions and 73 deletions

View file

@ -14,10 +14,20 @@ describe('applyTrailingSlash', () => {
expect(applyTrailingSlash('', undefined)).toEqual('');
});
test('should apply to /', () => {
test('should not apply to /', () => {
expect(applyTrailingSlash('/', true)).toEqual('/');
expect(applyTrailingSlash('/', false)).toEqual('');
expect(applyTrailingSlash('/', false)).toEqual('/');
expect(applyTrailingSlash('/', undefined)).toEqual('/');
expect(applyTrailingSlash('/?query#anchor', true)).toEqual(
'/?query#anchor',
);
expect(applyTrailingSlash('/?query#anchor', false)).toEqual(
'/?query#anchor',
);
expect(applyTrailingSlash('/?query#anchor', undefined)).toEqual(
'/?query#anchor',
);
});
test('should not apply to #anchor links ', () => {

View file

@ -9,8 +9,8 @@ export default function applyTrailingSlash(
path: string,
trailingSlash: boolean | undefined,
): string {
// Never apply trailing slash to an anchor link
if (path.startsWith('#')) {
// Never apply trailing slash to an anchor link
return path;
}
@ -29,8 +29,13 @@ export default function applyTrailingSlash(
// The trailing slash should be handled before the ?search#hash !
const [pathname] = path.split(/[#?]/);
const newPathname = trailingSlash
? addTrailingSlash(pathname)
: removeTrailingSlash(pathname);
// Never transform '/' to ''
const newPathname =
pathname === '/'
? '/'
: trailingSlash
? addTrailingSlash(pathname)
: removeTrailingSlash(pathname);
return path.replace(pathname, newPathname);
}