Skip to content

Commit

Permalink
feat: refactor app-tools (#5816)
Browse files Browse the repository at this point in the history
  • Loading branch information
caohuilin committed Jun 17, 2024
1 parent 38537fc commit 15a090c
Show file tree
Hide file tree
Showing 97 changed files with 1,484 additions and 1,129 deletions.
9 changes: 9 additions & 0 deletions .changeset/beige-rivers-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@modern-js/runtime': patch
'@modern-js/app-tools': patch
'@modern-js/utils': patch
---

feat: refactor app-tools command and analyze check entry point

feat: 重构 app-tools 命令和 analyze 插件识别入口逻辑
10 changes: 10 additions & 0 deletions packages/runtime/plugin-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@
"jsnext:source": "./src/router/runtime/server.ts",
"default": "./dist/esm/router/runtime/server.js"
},
"./router/cli": {
"types": "./dist/types/router/cli/index.d.ts",
"jsnext:source": "./src/router/cli/index.ts",
"default": "./dist/cjs/router/cli/index.js"
},
"./loadable-bundler-plugin": {
"types": "./dist/types/ssr/cli/loadable-bundler-plugin.d.ts",
"jsnext:source": "./src/ssr/cli/loadable-bundler-plugin.ts",
Expand Down Expand Up @@ -156,6 +161,9 @@
"router/server": [
"./dist/types/router/runtime/server.d.ts"
],
"router/cli": [
"./dist/types/router/cli/index.d.ts"
],
"loadable-bundler-plugin": [
"./dist/types/ssr/cli/loadable-bundler-plugin.d.ts"
]
Expand Down Expand Up @@ -185,11 +193,13 @@
"@modern-js/plugin": "workspace:*",
"@modern-js/types": "workspace:*",
"@modern-js/utils": "workspace:*",
"@modern-js/plugin-data-loader": "workspace:*",
"@modern-js/runtime-utils": "workspace:*",
"@types/loadable__component": "^5.13.4",
"@types/react-helmet": "^6.1.2",
"@types/styled-components": "^5.1.14",
"esbuild": "0.17.19",
"es-module-lexer": "^1.1.0",
"hoist-non-react-statics": "^3.3.2",
"invariant": "^2.2.4",
"react-helmet": "^6.1.0",
Expand Down
1 change: 1 addition & 0 deletions packages/runtime/plugin-runtime/src/cli/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const APP_FILE_NAME = 'App';
10 changes: 10 additions & 0 deletions packages/runtime/plugin-runtime/src/cli/entry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import path from 'path';
import { JS_EXTENSIONS, findExists } from '@modern-js/utils';
import { APP_FILE_NAME } from './constants';

const hasApp = (dir: string) =>
findExists(
JS_EXTENSIONS.map(ext => path.resolve(dir, `${APP_FILE_NAME}${ext}`)),
);

export const isRuntimeEntry = (dir: string) => hasApp(dir);
6 changes: 6 additions & 0 deletions packages/runtime/plugin-runtime/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { statePlugin } from '../state/cli';
import { ssrPlugin } from '../ssr/cli';
import { routerPlugin } from '../router/cli';
import { documentPlugin } from '../document/cli';
import { isRuntimeEntry } from './entry';

export { isRuntimeEntry } from './entry';

export const runtimePlugin = (): CliPlugin<AppTools> => ({
name: '@modern-js/runtime',
Expand All @@ -18,6 +21,9 @@ export const runtimePlugin = (): CliPlugin<AppTools> => ({
usePlugins: [ssrPlugin(), statePlugin(), routerPlugin(), documentPlugin()],
setup: api => {
return {
checkEntryPoint({ path, entry }) {
return { path, entry: entry || isRuntimeEntry(path) };
},
config() {
const appDir = api.useAppContext().appDirectory;
process.env.IS_REACT18 = isReact18(appDir).toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
FILE_SYSTEM_ROUTES_DYNAMIC_REGEXP,
FILE_SYSTEM_ROUTES_INDEX,
FILE_SYSTEM_ROUTES_LAYOUT,
} from '../constants';
} from '../../constants';
import { replaceWithAlias } from '../utils';
import { debug, findLayout, shouldSkip, getRouteWeight } from './utils';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import path from 'path';
import { fs } from '@modern-js/utils';
import type { Entrypoint, RouteLegacy } from '@modern-js/types';
import { makeLegalIdentifier } from '../makeLegalIdentifier';
import {
FILE_SYSTEM_ROUTES_COMPONENTS_DIR,
FILE_SYSTEM_ROUTES_DYNAMIC_REGEXP,
FILE_SYSTEM_ROUTES_INDEX,
FILE_SYSTEM_ROUTES_LAYOUT,
} from '../constants';
} from '../../constants';
import { replaceWithAlias } from '../utils';
import { makeLegalIdentifier } from '../makeLegalIdentifier';
import { debug, findLayout, shouldSkip, getRouteWeight } from './utils';

export type { RouteLegacy as Route };
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import path from 'path';
import { createDebugger, findExists, fs } from '@modern-js/utils';
import {
JS_EXTENSIONS,
createDebugger,
findExists,
fs,
} from '@modern-js/utils';
import {
FILE_SYSTEM_ROUTES_LAYOUT,
FILE_SYSTEM_ROUTES_GLOBAL_LAYOUT,
FILE_SYSTEM_ROUTES_IGNORED_REGEX,
} from '../constants';
} from '../../constants';

const debug = createDebugger('get-client-routes');

Expand Down
187 changes: 187 additions & 0 deletions packages/runtime/plugin-runtime/src/router/cli/code/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import path from 'path';
import {
fs,
getEntryOptions,
isRouterV5,
isSSGEntry,
isUseSSRBundle,
logger,
} from '@modern-js/utils';
import { IAppContext, PluginAPI } from '@modern-js/core';
import type {
Entrypoint,
Route,
RouteLegacy,
PageRoute,
SSRMode,
NestedRouteForCli,
} from '@modern-js/types';
import {
AppNormalizedConfig,
AppTools,
ImportStatement,
} from '@modern-js/app-tools';
import { FILE_SYSTEM_ROUTES_FILE_NAME } from '../constants';
import * as templates from './templates';
import { getClientRoutes, getClientRoutesLegacy } from './getClientRoutes';
import { getServerLoadersFile, getServerCombinedModueFile } from './utils';
import { walk } from './nestedRoutes';

export const generateCode = async (
appContext: IAppContext,
config: AppNormalizedConfig<'shared'>,
entrypoints: Entrypoint[],
api: PluginAPI<AppTools<'shared'>>,
) => {
const {
internalDirectory,
srcDirectory,
internalDirAlias,
internalSrcAlias,
packageName,
} = appContext;

const hookRunners = api.useHookRunners();

const isV5 = isRouterV5(config);
const getRoutes = isV5 ? getClientRoutesLegacy : getClientRoutes;
const importsStatemets = new Map<string, ImportStatement[]>();
const oldVersion =
typeof (config?.runtime.router as { oldVersion: boolean }) === 'object'
? Boolean((config?.runtime.router as { oldVersion: boolean }).oldVersion)
: false;

await Promise.all(entrypoints.map(generateEntryCode));

return {
importsStatemets,
};

async function generateEntryCode(entrypoint: Entrypoint) {
const { entryName, isMainEntry, isAutoMount, fileSystemRoutes } =
entrypoint;
if (isAutoMount) {
// generate routes file for file system routes entrypoint.
if (fileSystemRoutes) {
let initialRoutes: (NestedRouteForCli | PageRoute)[] | RouteLegacy[] =
[];
let nestedRoutes: NestedRouteForCli | NestedRouteForCli[] | null = null;
if (entrypoint.entry) {
initialRoutes = getRoutes({
entrypoint,
srcDirectory,
srcAlias: internalSrcAlias,
internalDirectory,
internalDirAlias,
});
}
if (!isV5 && entrypoint.nestedRoutesEntry) {
nestedRoutes = await walk(
entrypoint.nestedRoutesEntry,
entrypoint.nestedRoutesEntry,
{
name: internalSrcAlias,
basename: srcDirectory,
},
entrypoint.entryName,
entrypoint.isMainEntry,
oldVersion,
);
if (nestedRoutes) {
// eslint-disable-next-line max-depth
if (!Array.isArray(nestedRoutes)) {
nestedRoutes = [nestedRoutes];
}
// eslint-disable-next-line max-depth
for (const route of nestedRoutes) {
(initialRoutes as Route[]).unshift(route);
}
}
}

const { routes } = await hookRunners.modifyFileSystemRoutes({
entrypoint,
routes: initialRoutes,
});

const config = api.useResolvedConfigContext();
const ssr = getEntryOptions(
entryName,
isMainEntry,
config.server.ssr,
config.server.ssrByEntries,
packageName,
);
const useSSG = isSSGEntry(config, entryName, entrypoints);

let mode: SSRMode | undefined;
if (ssr) {
mode = typeof ssr === 'object' ? ssr.mode || 'string' : 'string';
}
if (mode === 'stream') {
const hasPageRoute = routes.some(
route => 'type' in route && route.type === 'page',
);
if (hasPageRoute) {
logger.error(
'Streaming ssr is not supported when pages dir exists',
);
// eslint-disable-next-line no-process-exit
process.exit(1);
}
}

const { code } = await hookRunners.beforeGenerateRoutes({
entrypoint,
code: await templates.fileSystemRoutes({
routes,
ssrMode: useSSG ? 'string' : mode,
nestedRoutesEntry: entrypoint.nestedRoutesEntry,
entryName: entrypoint.entryName,
internalDirectory,
splitRouteChunks: config?.output?.splitRouteChunks,
}),
});

// extract nested router loaders
if (entrypoint.nestedRoutesEntry && isUseSSRBundle(config)) {
const routesServerFile = getServerLoadersFile(
internalDirectory,
entryName,
);

const code = templates.routesForServer({
routes: routes as (NestedRouteForCli | PageRoute)[],
});

await fs.ensureFile(routesServerFile);
await fs.writeFile(routesServerFile, code);
}

const serverLoaderCombined = templates.ssrLoaderCombinedModule(
entrypoints,
entrypoint,
config,
appContext,
);
if (serverLoaderCombined) {
const serverLoaderFile = getServerCombinedModueFile(
internalDirectory,
entryName,
);

await fs.outputFile(serverLoaderFile, serverLoaderCombined);
}

fs.outputFileSync(
path.resolve(
internalDirectory,
`./${entryName}/${FILE_SYSTEM_ROUTES_FILE_NAME}`,
),
code,
'utf8',
);
}
}
}
};
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import * as path from 'path';
import { fs, normalizeToPosixPath } from '@modern-js/utils';
import { JS_EXTENSIONS, fs, normalizeToPosixPath } from '@modern-js/utils';
import type { NestedRouteForCli } from '@modern-js/types';
import { getPathWithoutExt } from '../utils/routes';
import { JS_EXTENSIONS, NESTED_ROUTE } from './constants';
import { hasAction, replaceWithAlias } from './utils';
import { NESTED_ROUTE } from '../constants';
import { getPathWithoutExt, hasAction, replaceWithAlias } from './utils';

const conventionNames = Object.values(NESTED_ROUTE);

Expand Down
Loading

0 comments on commit 15a090c

Please sign in to comment.