Skip to content

Commit

Permalink
refactor: prefetch to preload and extract as utils
Browse files Browse the repository at this point in the history
  • Loading branch information
PeachScript committed Jan 26, 2024
1 parent aba626e commit 786e746
Show file tree
Hide file tree
Showing 8 changed files with 102 additions and 85 deletions.
4 changes: 2 additions & 2 deletions packages/preset-umi/.fatherrc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ export default defineConfig({
ignores: ['src/client/*'],
},
umd: {
entry: 'src/client/prefetchRouteFilesScp.ts',
entry: 'src/client/preloadRouteFilesScp.ts',
output: 'templates/routePrefetch',
chainWebpack(memo) {
memo.output.filename('prefetchRouteFilesScp.js');
memo.output.filename('preloadRouteFilesScp.js');
memo.output.delete('libraryTarget');
memo.output.iife(true);

Expand Down
19 changes: 0 additions & 19 deletions packages/preset-umi/src/client/prefetchRouteFilesScp.ts

This file was deleted.

48 changes: 48 additions & 0 deletions packages/preset-umi/src/client/preloadRouteFilesScp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* NOTE: DO NOT USE ADVANCED SYNTAX IN THIS FILE, TO AVOID INSERT HELPERS TO REDUCE SCRIPT SIZE.
*/

import { getPreloadRouteFiles } from '../features/routePrefetch/utils';

const basename = '{{basename}}';
const publicPath = '{{publicPath}}';
const pathname = location.pathname;
const routePath =
pathname.startsWith(basename) &&
decodeURI(`/${pathname.slice(basename.length)}`);

// skip preload if basename not match
if (routePath) {
const map = '{{routeChunkFilesMap}}' as any;
const doc = document;
const head = doc.head;
const createElement = doc.createElement.bind(doc);
const files = getPreloadRouteFiles(routePath, map, {
publicPath,
});

files?.forEach((file) => {
const type = file.type;
const url = file.url;
let tag: HTMLLinkElement | HTMLScriptElement;

if (type === 'js') {
tag = createElement('script');
tag.src = url;
tag.async = true;
} else if (type === 'css') {
tag = createElement('link');
tag.href = url;
tag.rel = 'preload';
tag.as = 'style';
} else {
return;
}

file.attrs.forEach((attr) => {
tag.setAttribute(attr[0], attr[1] || '');
});

head.appendChild(tag);
});
}

This file was deleted.

10 changes: 5 additions & 5 deletions packages/preset-umi/src/features/routePrefetch/routePrefetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { dirname, isAbsolute, join, relative } from 'path';
import { TEMPLATES_DIR } from '../../constants';
import { createResolver } from '../../libs/scan';
import type { IApi, IRoute } from '../../types';
import { PREFETCH_ROUTE_MAP_SCP_TYPE } from './prefetchRouteFiles';
import { PRELOAD_ROUTE_MAP_SCP_TYPE } from './utils';

export interface IRouteChunkFilesMap {
/**
Expand Down Expand Up @@ -95,15 +95,15 @@ export default (api: IApi) => {
? // map mode
[
{
type: PREFETCH_ROUTE_MAP_SCP_TYPE,
type: PRELOAD_ROUTE_MAP_SCP_TYPE,
content: JSON.stringify(routeChunkFilesMap),
},
]
: // script mode
[
{
content: readFileSync(
join(TEMPLATES_DIR, 'routePrefetch/prefetchRouteFilesScp.js'),
join(TEMPLATES_DIR, 'routePrefetch/preloadRouteFilesScp.js'),
'utf-8',
)
.replace(
Expand Down Expand Up @@ -147,7 +147,7 @@ export default (api: IApi) => {
);
} catch (err) {
logger.error(
`[routePrefetch]: route file resolve error, cannot prefetch for ${origin.request!}`,
`[routePrefetch]: route file resolve error, cannot preload for ${origin.request!}`,
);
continue;
}
Expand Down Expand Up @@ -205,7 +205,7 @@ export default (api: IApi) => {
files.push(fileAbsPath);
} catch {
logger.error(
`[routePrefetch]: route file resolve error, cannot prefetch for ${current.file}`,
`[routePrefetch]: route file resolve error, cannot preload for ${current.file}`,
);
}
current = current.parentId && api.appData.routes[current.parentId];
Expand Down
46 changes: 46 additions & 0 deletions packages/preset-umi/src/features/routePrefetch/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* NOTE: DO NOT USE ADVANCED SYNTAX IN THIS FILE, TO AVOID INSERT HELPERS TO REDUCE SCRIPT SIZE.
*/

import type { IRouteChunkFilesMap } from './routePrefetch';

interface IPreloadRouteFile {
type: 'js' | 'css' | unknown;
url: string;
attrs: ([string, string] | [string])[];
}

export const PRELOAD_ROUTE_MAP_SCP_TYPE = 'umi-route-chunk-files-map';

export function getPreloadRouteFiles(
path: string,
map: IRouteChunkFilesMap,
opts: { publicPath: string },
): IPreloadRouteFile[] | undefined {
const matched: IRouteChunkFilesMap['r'][string] | undefined =
// search for static route
map.r[path] ||
// search for dynamic route
Object.entries(map.r).find((p) => {
const route = p[0];
const reg = new RegExp(
// replace /:id to /[^/]+
// replace /* to /.+
`^${route.replace(/\/:[^/]+/g, '/[^/]+').replace('/*', '/.+')}$`,
);

return reg.test(path);
})?.[1];

return matched?.map((i) => {
const id = map.f[i][1];
const file = map.f[i][0];
const ext = file.split('.').pop();

return {
type: ext,
url: `${opts.publicPath}${file}`,
attrs: [[`data-${map.b}`, `${map.p}:${id}`]],
};
});
}

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 786e746

Please sign in to comment.