parent
d2241a4187
commit
7de426f483
@ -0,0 +1,12 @@
|
||||
import NextLink, { LinkProps } from 'next/link';
|
||||
import React from 'react';
|
||||
import addBasePath from '../../utils/addBasePath';
|
||||
|
||||
const Link: React.FC<LinkProps> = ({ href, ...props }) => {
|
||||
if (props.as) {
|
||||
props.as = addBasePath(props.as);
|
||||
}
|
||||
return <NextLink href={addBasePath(href)} {...props} />;
|
||||
};
|
||||
|
||||
export default Link;
|
@ -0,0 +1,67 @@
|
||||
import { NextRouter, useRouter as useNextRouter } from 'next/router';
|
||||
import { useMemo } from 'react';
|
||||
import addBasePath from '../utils/addBasePath';
|
||||
|
||||
const basePath = addBasePath('');
|
||||
|
||||
const urlPropertyFields = [
|
||||
'pathname',
|
||||
'events',
|
||||
'route',
|
||||
'query',
|
||||
'asPath',
|
||||
'components',
|
||||
'isFallback',
|
||||
'basePath',
|
||||
'locale',
|
||||
'locales',
|
||||
'defaultLocale',
|
||||
'isReady',
|
||||
'isPreview',
|
||||
'isLocaleDomain',
|
||||
'domainLocales',
|
||||
];
|
||||
|
||||
const coreMethodFields = ['reload', 'back', 'prefetch', 'beforePopState'];
|
||||
|
||||
const wrapRouter = (target: any): NextRouter => {
|
||||
const router = {
|
||||
push(url: URL, as?: URL, options?: never) {
|
||||
return target.push(
|
||||
addBasePath(url),
|
||||
as ? addBasePath(as) : undefined,
|
||||
options
|
||||
);
|
||||
},
|
||||
replace(url: URL, as?: URL, options?: never) {
|
||||
return target.push(
|
||||
addBasePath(url),
|
||||
as ? addBasePath(as) : undefined,
|
||||
options
|
||||
);
|
||||
},
|
||||
get basePath() {
|
||||
return basePath;
|
||||
},
|
||||
};
|
||||
|
||||
urlPropertyFields.forEach((field: string) => {
|
||||
Object.defineProperty(router, field, {
|
||||
get() {
|
||||
return target[field] as string;
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
coreMethodFields.forEach((field: string) => {
|
||||
(router as any)[field] = (...args: any[]) => {
|
||||
return target[field](...args);
|
||||
};
|
||||
});
|
||||
return router as NextRouter;
|
||||
};
|
||||
|
||||
export const useRouter = (): NextRouter => {
|
||||
const router = useNextRouter();
|
||||
return useMemo(() => wrapRouter(router), [router]);
|
||||
};
|
@ -0,0 +1,20 @@
|
||||
import getConfig from 'next/config';
|
||||
import { UrlObject } from 'url';
|
||||
|
||||
const {
|
||||
publicRuntimeConfig: { basePath = '' },
|
||||
} = getConfig();
|
||||
|
||||
declare type Url = string | UrlObject;
|
||||
|
||||
export default function addBasePath(url: UrlObject): UrlObject;
|
||||
export default function addBasePath(url: string): string;
|
||||
export default function addBasePath(url: Url): Url;
|
||||
export default function addBasePath(url: Url): Url {
|
||||
if (typeof url === 'string') {
|
||||
return basePath + url;
|
||||
}
|
||||
|
||||
url.pathname = basePath + url.pathname;
|
||||
return url;
|
||||
}
|
Loading…
Reference in new issue