fix(v2): sitemap plugin should handle siteConfig.trailingSlash automatically (#4950)

* create new @docusaurus/utils-common and move applyTrailingSlash there

* sitemap plugin should handle siteConfig.trailingSlash automatically

* typo
This commit is contained in:
Sébastien Lorber 2021-06-14 20:04:39 +02:00 committed by GitHub
parent 4e5f0febb9
commit aeb8e9da51
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 127 additions and 35 deletions

View file

@ -0,0 +1,36 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default function applyTrailingSlash(
path: string,
trailingSlash: boolean | undefined,
): string {
// Never apply trailing slash to an anchor link
if (path.startsWith('#')) {
return path;
}
// TODO deduplicate: also present in @docusaurus/utils
function addTrailingSlash(str: string): string {
return str.endsWith('/') ? str : `${str}/`;
}
function removeTrailingSlash(str: string): string {
return str.endsWith('/') ? str.slice(0, -1) : str;
}
// undefined = legacy retrocompatible behavior
if (typeof trailingSlash === 'undefined') {
return path;
}
// The trailing slash should be handled before the ?search#hash !
const [pathname] = path.split(/[#?]/);
const newPathname = trailingSlash
? addTrailingSlash(pathname)
: removeTrailingSlash(pathname);
return path.replace(pathname, newPathname);
}