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: optimize runtime code when dataLoader is not defined #6849

Merged
merged 3 commits into from
Apr 9, 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/wicked-points-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@ice/runtime': patch
'@ice/app': patch
---

feat: remove runtime code when loaders is not export
10 changes: 8 additions & 2 deletions packages/ice/src/createService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,8 @@ async function createService({ rootDir, command, commandArgs }: CreateServiceOpt
// Only when code splitting use the default strategy or set to `router`, the router will be lazy loaded.
const lazy = [true, 'chunks', 'page', 'page-vendors'].includes(userConfig.codeSplitting);
const { routeImports, routeDefinition } = getRoutesDefinition(routesInfo.routes, lazy);
const loaderExports = hasExportAppData || Boolean(routesInfo.loaders);
const hasDataLoader = Boolean(userConfig.dataLoader) && loaderExports;
// add render data
generator.setRenderData({
...routesInfo,
Expand All @@ -289,13 +291,13 @@ async function createService({ rootDir, command, commandArgs }: CreateServiceOpt
jsOutput: distType.includes('javascript'),
hasDocument: fse.existsSync(path.join(rootDir, 'src/document.tsx')) || fse.existsSync(path.join(rootDir, 'src/document.jsx')) || fse.existsSync(path.join(rootDir, 'src/document.js')),
dataLoader: userConfig.dataLoader,
hasDataLoader,
routeImports,
routeDefinition,
});
dataCache.set('routes', JSON.stringify(routesInfo));
dataCache.set('hasExportAppData', hasExportAppData ? 'true' : '');

const hasDataLoader = Boolean(userConfig.dataLoader) && (hasExportAppData || Boolean(routesInfo.loaders));
// Render exports files if route component export dataLoader / pageConfig.
renderExportsTemplate(
{
Expand Down Expand Up @@ -379,7 +381,11 @@ async function createService({ rootDir, command, commandArgs }: CreateServiceOpt

const appConfig: AppConfig = (await getAppConfig()).default;

updateRuntimeEnv(appConfig, { disableRouter });
updateRuntimeEnv(appConfig, {
disableRouter,
// The optimization for runtime size should only be enabled in production mode.
dataLoader: command !== 'build' || loaderExports,
});

return {
run: async () => {
Expand Down
21 changes: 17 additions & 4 deletions packages/ice/src/utils/runtimeEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface Envs {
}
interface EnvOptions {
disableRouter: boolean;
dataLoader: boolean;
}

const expandedEnvs = {};
Expand Down Expand Up @@ -50,24 +51,36 @@ export async function setEnv(
process.env.ICE_CORE_ROUTER = 'true';
process.env.ICE_CORE_ERROR_BOUNDARY = 'true';
process.env.ICE_CORE_INITIAL_DATA = 'true';
// Set to false for compatibility with the old version.
process.env.ICE_CORE_REMOVE_DATA_LOADER = 'false';

// set ssr and ssg env to false, for remove dead code in CSR.
process.env.ICE_CORE_SSG = 'false';
process.env.ICE_CORE_SSR = 'false';
}

export const updateRuntimeEnv = (appConfig: AppConfig, options: EnvOptions) => {
const { disableRouter } = options;
const { disableRouter, dataLoader } = options;
if (!appConfig?.app?.errorBoundary) {
process.env['ICE_CORE_ERROR_BOUNDARY'] = 'false';
process.env.ICE_CORE_ERROR_BOUNDARY = 'false';
}
if (disableRouter) {
process.env['ICE_CORE_ROUTER'] = 'false';
process.env.ICE_CORE_ROUTER = 'false';
}
if (!dataLoader) {
process.env.ICE_CORE_REMOVE_DATA_LOADER = 'true';
}
};

export function getCoreEnvKeys() {
return ['ICE_CORE_MODE', 'ICE_CORE_ROUTER', 'ICE_CORE_ERROR_BOUNDARY', 'ICE_CORE_INITIAL_DATA', 'ICE_CORE_DEV_PORT'];
return [
'ICE_CORE_MODE',
'ICE_CORE_ROUTER',
'ICE_CORE_ERROR_BOUNDARY',
'ICE_CORE_INITIAL_DATA',
'ICE_CORE_DEV_PORT',
'ICE_CORE_REMOVE_DATA_LOADER',
];
}

export function getExpandedEnvs(): Record<string, string> {
Expand Down
7 changes: 4 additions & 3 deletions packages/ice/templates/core/entry.client.tsx.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as app from '@/app';
import createRoutes from './routes';
<% } -%>
<%- runtimeOptions.imports %>
<% if (dataLoaderImport.imports) {-%><%-dataLoaderImport.imports%><% } -%>
<% if (dataLoaderImport.imports && hasDataLoader) {-%><%-dataLoaderImport.imports%><% } -%>
import type { RunClientAppOptions } from '@ice/runtime';

const getRouterBasename = () => {
Expand All @@ -19,7 +19,7 @@ const getRouterBasename = () => {
// Otherwise chunk of route component will pack @ice/jsx-runtime and depend on framework bundle.
const App = <></>;

<% if (!dataLoaderImport.imports) {-%>
<% if (!dataLoaderImport.imports && hasDataLoader) {-%>
let dataLoaderFetcher = (options) => {
return window.fetch(options.url, options);
}
Expand All @@ -39,8 +39,9 @@ const renderOptions: RunClientAppOptions = {
basename: getRouterBasename(),
hydrate: <%- hydrate %>,
memoryRouter: <%- memoryRouter || false %>,
<% if (hasDataLoader) { -%>
dataLoaderFetcher,
dataLoaderDecorator,
dataLoaderDecorator,<% } -%>
runtimeOptions: {
<% if (runtimeOptions.exports) { -%>
<%- runtimeOptions.exports %>
Expand Down
18 changes: 10 additions & 8 deletions packages/runtime/src/appData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AppExport, AppData, RequestContext } from './types.js';
import type { AppExport, AppData, RequestContext, Loader } from './types.js';
import { callDataLoader } from './dataLoader.js';

/**
Expand All @@ -18,15 +18,17 @@ async function getAppData(appExport: AppExport, requestContext?: RequestContext)
return null;
}

let loader;
if (process.env.ICE_CORE_REMOVE_DATA_LOADER !== 'true') {
let loader: Loader;

if (typeof appDataLoaderConfig === 'function' || Array.isArray(appDataLoaderConfig)) {
loader = appDataLoaderConfig;
} else {
loader = appDataLoaderConfig.loader;
}
if (typeof appDataLoaderConfig === 'function' || Array.isArray(appDataLoaderConfig)) {
loader = appDataLoaderConfig;
} else {
loader = appDataLoaderConfig.loader;
}

return await callDataLoader(loader, requestContext);
return await callDataLoader(loader, requestContext);
}
}

export {
Expand Down
10 changes: 6 additions & 4 deletions packages/runtime/src/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,12 @@ export function createRouteLoader(options: RouteLoaderOptions): LoaderFunction {

const getData = (requestContext: RequestContext) => {
let routeData: any;
if (globalLoader) {
routeData = globalLoader.getData(routeId, { renderMode, requestContext });
} else {
routeData = callDataLoader(loader, requestContext);
if (process.env.ICE_CORE_REMOVE_DATA_LOADER !== 'true') {
if (globalLoader) {
routeData = globalLoader.getData(routeId, { renderMode, requestContext });
} else {
routeData = callDataLoader(loader, requestContext);
}
}
return routeData;
};
Expand Down
6 changes: 4 additions & 2 deletions packages/runtime/src/runClientApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,10 @@ export default async function runClientApp(options: RunClientAppOptions) {
await Promise.all(runtimeModules.statics.map(m => runtime.loadModule(m)).filter(Boolean));
}

dataLoaderFetcher && setFetcher(dataLoaderFetcher);
dataLoaderDecorator && setDecorator(dataLoaderDecorator);
if (process.env.ICE_CORE_REMOVE_DATA_LOADER !== 'true') {
dataLoaderFetcher && setFetcher(dataLoaderFetcher);
dataLoaderDecorator && setDecorator(dataLoaderDecorator);
}

if (!appData) {
appData = await getAppData(app, requestContext);
Expand Down
Loading