Skip to content

Commit

Permalink
fix: deal with json file when use on-demand compile (#6548)
Browse files Browse the repository at this point in the history
* fix: deal with json file when use on-demand compile

* chore: changeset
  • Loading branch information
ClarkXia authored Sep 27, 2023
1 parent 4d256e3 commit 6f18c3d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/long-mayflies-smoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ice/app': patch
---

fix: deal with json file when use on-demand compile
4 changes: 4 additions & 0 deletions examples/csr-project/ice.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export default defineConfig(() => ({
}
return webpackConfig;
},
server: {
onDemand: true,
format: 'esm',
},
dropLogLevel: 'warn',
plugins: [
auth(),
Expand Down
19 changes: 17 additions & 2 deletions packages/ice/src/service/ServerRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ interface InitOptions {
type ResolveCallback = Parameters<PluginBuild['onResolve']>[1];
type LoadCallback = Parameters<PluginBuild['onLoad']>[1];

const FALLBACK_LOADERS = {
'.json': 'json',
'.txt': 'text',
};

function getPluginLifecycle(plugin: Plugin, compiler: 'onLoad'): [OnResolveOptions, LoadCallback][];
function getPluginLifecycle(plugin: Plugin, compiler: 'onResolve'): [OnResolveOptions, ResolveCallback][];
function getPluginLifecycle(plugin: Plugin, hookKey: 'onResolve' | 'onLoad') {
Expand Down Expand Up @@ -263,11 +268,21 @@ class ServerRunner extends Runner {
...args,
path: formatedId,
});

// If res is undefined, it means the plugin does not handle the file, fallback to default handler.
if (!res && FALLBACK_LOADERS[path.extname(formatedId)]) {
res = {
loader: FALLBACK_LOADERS[path.extname(formatedId)],
};
}
if (res) {
const { contents, loader } = res;
if (['json', 'text'].includes(loader)) {
code = `__ice_exports__.default = ${contents || JSON.stringify(await fse.readFile(formatedId, 'utf-8'))}`;
if (contents) {
code = `__ice_exports__.default = ${contents}`;
} else {
const contents = await fse.readFile(formatedId, 'utf-8');
code = `__ice_exports__.default = ${loader === 'text' ? JSON.stringify(contents) : contents}`;
}
} else {
code = typeof contents === 'string' ? contents : contents.toString();
}
Expand Down

0 comments on commit 6f18c3d

Please sign in to comment.