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

fix: ssr inline assets #4907

Merged
merged 5 commits into from
Nov 3, 2023
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/sweet-rabbits-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modern-js/runtime': patch
---

fix(ssr): ssr enable inline assets in production env
fix(ssr): ssr 能够在开发环境 inline 静态文件
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ const checkIsInline = (
}
};

const readAsset = async (chunk: ChunkAsset) => {
// working node env
const fs = await import('node:fs/promises');
const path = await import('node:path');

// only working in 'production' env
// we need ensure the assetsDir is same as ssr bundles.
const filepath = path.resolve(__dirname, chunk.filename!);

return fs.readFile(filepath, 'utf-8');
};

const checkIsNode = () =>
typeof process !== 'undefined' && process.release?.name === 'node';

Expand Down Expand Up @@ -132,18 +144,18 @@ class LoadableCollector implements Collector {
);
})
.map(async chunk => {
const script = `<script${attributes} src="${chunk.url}"></script>`;

// only in node read assets
if (checkIsInline(chunk, enableInlineScripts) && checkIsNode()) {
const fs = await import('node:fs/promises');
const filepath = chunk.path!;
return fs
.readFile(filepath, 'utf-8')
return readAsset(chunk)
.then(content => `<script>${content}</script>`)
.catch(_ => {
// ignore error, then return a empty string.
return '';
// if read file occur error, we should return script tag to import js assets.
return script;
});
} else {
return `<script${attributes} src="${chunk.url}"></script>`;
return script;
}
}),
);
Expand Down Expand Up @@ -171,17 +183,18 @@ class LoadableCollector implements Collector {
);
})
.map(async chunk => {
const link = `<link${atrributes} href="${chunk.url!}" rel="stylesheet" />`;

// only in node read asserts
if (checkIsInline(chunk, enableInlineStyles) && checkIsNode()) {
const fs = await import('node:fs/promises');
return fs
.readFile(chunk.path!)
return readAsset(chunk)
.then(content => `<style>${content}</style>`)
.catch(_ => {
// ignore error, then return a empty string.
return '';
// if read file occur error, we should return link to import css assets.
return link;
});
} else {
return `<link${atrributes} href="${chunk.url!}" rel="stylesheet" />`;
return link;
}
}),
);
Expand Down