Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server): support getting assets on the server #5896

Merged
merged 3 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/bright-adults-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modern-js/plugin-server': patch
---

feat: support getting assets on the server
feat: 支持在服务端获取静态资源
25 changes: 20 additions & 5 deletions packages/server/plugin-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@
"types": "./dist/types/server.d.ts",
"jsnext:source": "./src/server.ts",
"default": "./dist/cjs/server.js"
},
"./runtime": {
"types": "./dist/types/runtime/node.d.ts",
"default": "./dist/cjs/runtime/node.js"
},
"./runtime/worker": {
"types": "./dist/types/runtime/worker.d.ts",
"default": "./dist/esm-node/runtime/worker.js"
}
},
"scripts": {
Expand All @@ -53,25 +61,32 @@
],
"server": [
"./dist/types/server.d.ts"
],
"runtime": [
"./dist/types/runtime/node.d.ts"
],
"runtime/worker": [
"./dist/types/runtime/worker.d.ts"
]
}
},
"dependencies": {
"@modern-js/utils": "workspace:*",
"@modern-js/runtime-utils": "workspace:*",
"@modern-js/server-utils": "workspace:*",
"@modern-js/utils": "workspace:*",
"@swc/helpers": "0.5.3"
},
"devDependencies": {
"@modern-js/server-core": "workspace:*",
"@modern-js/app-tools": "workspace:*",
"@modern-js/core": "workspace:*",
"@scripts/build": "workspace:*",
"@modern-js/server-core": "workspace:*",
"@modern-js/types": "workspace:*",
"typescript": "^5",
"@scripts/build": "workspace:*",
"@scripts/jest-config": "workspace:*",
"@types/jest": "^29",
"@types/node": "^14",
"jest": "^29",
"@scripts/jest-config": "workspace:*"
"typescript": "^5"
},
"sideEffects": [
"*.css",
Expand Down
111 changes: 111 additions & 0 deletions packages/server/plugin-server/src/runtime/assets/assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { matchRoutes } from '@modern-js/runtime-utils/remix-router';
import { matchEntry } from '@modern-js/runtime-utils/node';

const createScript = (href: string, nonce?: string) =>
`<script defer src="${href}"${nonce ? ` nonce="${nonce}"` : ''}></script>`;

const createCss = (href: string) =>
`<link rel="stylesheet" type="text/css" href="${href}">`;

export const getAssets = (
html: string,
nestedRoutes: Record<string, any>,
routesJson: Record<string, any>,
routesManifest: Record<string, any>,
pathname: string,
) => {
const serverRoutes = routesJson.routes;
const entry = matchEntry(pathname, serverRoutes);

if (!entry) {
return {};
}

const { entryName } = entry;
if (!entryName) {
return {};
}

const entryRoutes = nestedRoutes[entryName];
if (!entryRoutes) {
return {};
}

const { routeAssets } = routesManifest;
const matches = matchRoutes(entryRoutes, pathname, entry.urlPath);

const assets = matches?.reduce((acc, match) => {
const routeId = match.route.id;
if (routeId) {
const matchedManifest = routeAssets[routeId];
const assets = matchedManifest?.assets;
if (Array.isArray(assets)) {
acc.push(...assets);
}
}
return acc;
}, [] as string[]);

const cssAssets = assets
?.filter(asset => asset.endsWith('.css'))
.filter(asset => !html.includes(asset));

const jsAssets = assets
?.filter(asset => asset.endsWith('.js'))
.filter(asset => !asset.includes('hot-update'))
.filter(asset => !html.includes(asset));

return {
cssAssets,
jsAssets,
};
};

export const getAssetsTags = (
html: string,
nestedRoutes: Record<string, any>,
routesJson: Record<string, any>,
routesManifest: Record<string, any>,
pathname: string,
nonce?: string,
) => {
const { cssAssets, jsAssets } = getAssets(
html,
nestedRoutes,
routesJson,
routesManifest,
pathname,
);

const cssLinks = cssAssets?.map(createCss);
const scripts = jsAssets?.map(asset => createScript(asset, nonce));

return {
cssLinks,
scripts,
};
};

export const injectAssetsTags = (
html: string,
cssLinks?: string[],
scripts?: string[],
): string => {
let injectedHtml = html;

if (cssLinks && cssLinks.length > 0) {
injectedHtml = injectedHtml.replace(
'</head>',
`${cssLinks.join('\n')}</head>`,
);
}

if (scripts && scripts.length > 0) {
injectedHtml = injectedHtml.replace(
`</body>`,
`${scripts.join('\n')}</body>`,
);
}

return injectedHtml;
};
63 changes: 63 additions & 0 deletions packages/server/plugin-server/src/runtime/assets/node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import path from 'node:path';
import fs from 'fs';
import {
NESTED_ROUTE_SPEC_FILE,
ROUTE_SPEC_FILE,
} from '@modern-js/utils/universal/constants';
import { ROUTE_MANIFEST_FILE } from '@modern-js/utils';
import { getAssetsTags, injectAssetsTags } from './assets';

export { getAssetsTags, getAssets } from './assets';

export const injectAssets = async ({
html,
pathname,
distDir,
nonce,
}: {
html: string;
pathname?: string;
distDir: string;
nonce?: string;
}) => {
// If is not CSR, return html
if (
typeof html !== 'string' ||
html?.includes('window._SSR_DATA') ||
!pathname
) {
return html;
}

try {
const nestedRoutesSpec = path.join(distDir, NESTED_ROUTE_SPEC_FILE);
if (!fs.existsSync(nestedRoutesSpec)) {
return html;
}

let injectedHtml = html;
const routesJson = await import(path.join(distDir, ROUTE_SPEC_FILE));
const nestedRouteSpec = await import(nestedRoutesSpec);
const routesManifest = await import(
path.join(distDir, ROUTE_MANIFEST_FILE)
);

const { cssLinks, scripts } = getAssetsTags(
html,
nestedRouteSpec,
routesJson,
routesManifest,
pathname,
nonce,
);

injectedHtml = injectAssetsTags(injectedHtml, cssLinks, scripts);

return injectedHtml;
} catch (error) {
if (process.env.NODE_ENV === 'development') {
console.error(error);
}
return html;
}
};
52 changes: 52 additions & 0 deletions packages/server/plugin-server/src/runtime/assets/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { getAssetsTags, injectAssetsTags } from './assets';

export { getAssetsTags, getAssets } from './assets';

export const injectAssets = async ({
html,
pathname,
nonce,
nestedRoutes,
routesManifest,
routesJson,
}: {
html: string;
pathname?: string;
nonce?: string;
nestedRoutes: Record<string, any>;
routesManifest: Record<string, any>;
routesJson: Record<string, any>;
}) => {
if (
typeof html !== 'string' ||
html?.includes('window._SSR_DATA') ||
!pathname
) {
return html;
}

try {
if (!nestedRoutes || !routesManifest || !routesJson) {
return html;
}

let injectedHtml = html;
const { cssLinks, scripts } = getAssetsTags(
html,
nestedRoutes,
routesJson,
routesManifest,
pathname,
nonce,
);

injectedHtml = injectAssetsTags(injectedHtml, cssLinks, scripts);

return injectedHtml;
} catch (error) {
if (process.env.NODE_ENV === 'development') {
console.error(error);
}
return html;
}
};
1 change: 1 addition & 0 deletions packages/server/plugin-server/src/runtime/node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { injectAssets, getAssetsTags } from './assets/node';
1 change: 1 addition & 0 deletions packages/server/plugin-server/src/runtime/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { injectAssets, getAssetsTags } from './assets/worker';
Loading
Loading