Skip to content

Commit 48d3bc7

Browse files
committedJul 27, 2024
feat: 支持构建时输出路由表
1 parent 32222a6 commit 48d3bc7

File tree

5 files changed

+43
-27
lines changed

5 files changed

+43
-27
lines changed
 

Diff for: ‎packages/unplugin-react-pages/client.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
declare module 'virtual:react-app' {
1+
declare module 'virtual:react-pages' {
22
import type { RouteObject } from 'react-router-dom';
33

44
export const routes: RouteObject[];

Diff for: ‎packages/unplugin-react-pages/src/core/FSRouter.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,8 @@ export class FSRouter {
185185
'/**',
186186
' * generated by pkg-name-for-test@pkg-version-for-test',
187187
' * @ref https://github.com/FrontEndDev-org/unplugin-react-pages',
188-
' * @ref https://reactrouter.com/',
188+
' * @ref https://react.dev',
189+
' * @ref https://reactrouter.com',
189190
' */',
190191
'',
191192
'import { Suspense, lazy, createElement } from "react";',

Diff for: ‎packages/unplugin-react-pages/src/core/ReactApp.ts renamed to ‎packages/unplugin-react-pages/src/core/ReactPages.ts

+30-15
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,29 @@ import { ensureArray } from '../helpers';
77
import type { PluginOptions } from '../plugin';
88
import { FSTree } from './FSTree';
99

10-
export type ReactAppChange = (this: ReactApp) => unknown;
11-
export class ReactApp {
10+
export type ReactPagesChange = (this: ReactPages) => unknown;
11+
export class ReactPages {
1212
logger: Logger;
1313
fsTree: FSTree;
14-
absApp: string;
14+
absPagesDir: string;
1515

1616
constructor(
1717
readonly options: PluginOptions,
1818
readonly config: ResolvedConfig,
1919
) {
2020
this.logger = createLogger(options.logLevel, { prefix: `[${pkgName}]` });
2121
this.logger.info(`new Options: ${JSON.stringify(options)}`);
22-
this.absApp = nodePath.join(this.config.root, options.appDir);
22+
this.absPagesDir = nodePath.join(this.config.root, options.pagesDir);
2323
this.fsTree = new FSTree({
24-
cwd: nodePath.join('/', options.appDir),
24+
cwd: nodePath.join('/', options.pagesDir),
2525
logger: this.logger,
2626
resolveFileName: (page, fileType) => {
2727
const fileNames = ensureArray(this.options.fileNames[fileType]);
2828
if (fileNames.length === 0)
2929
return;
3030

3131
return fileNames.find((fileName) => {
32-
const absFile = nodePath.join(this.absApp, page.dirName, fileName);
32+
const absFile = nodePath.join(this.absPagesDir, page.dirName, fileName);
3333
return nodeFS.existsSync(absFile) && nodeFS.statSync(absFile).isFile();
3434
});
3535
},
@@ -46,39 +46,44 @@ export class ReactApp {
4646
});
4747
}
4848

49-
get output() {
49+
async generate() {
50+
if (!this.isSetup) {
51+
this.logger.info(`is not setup, try to setup again`);
52+
await this.setup();
53+
}
54+
5055
const output = this.fsTree.render();
5156
this.logger.info(`Generated: ${output}`);
5257
return output;
5358
}
5459

55-
private _inApp(path: string) {
56-
return path.startsWith(this.absApp);
60+
private _inPagesDir(path: string) {
61+
return path.startsWith(this.absPagesDir);
5762
}
5863

5964
private devServer?: ViteDevServer;
6065
private onChange?: () => unknown;
61-
async connect(devServer: ViteDevServer, onChange: ReactAppChange) {
66+
async watch(devServer: ViteDevServer, onChange: ReactPagesChange) {
6267
this.devServer = devServer;
6368
this.onChange = onChange;
6469
this.logger.info(`setup`);
6570

6671
devServer.watcher.on('unlink', async (path) => {
67-
if (!this._inApp(path))
72+
if (!this._inPagesDir(path))
6873
return;
6974

7075
await this.removeFile(path);
7176
});
7277

7378
devServer.watcher.on('add', async (path) => {
74-
if (!this._inApp(path))
79+
if (!this._inPagesDir(path))
7580
return;
7681

7782
await this.addFile(path);
7883
});
7984

8085
devServer.watcher.on('change', async (path) => {
81-
if (!this._inApp(path))
86+
if (!this._inPagesDir(path))
8287
return;
8388

8489
await this.updateFile(path);
@@ -87,16 +92,26 @@ export class ReactApp {
8792
await this.setup();
8893
}
8994

95+
private _isSetup = false;
96+
get isSetup() {
97+
return this._isSetup;
98+
}
99+
90100
async setup() {
91-
this.logger.info(`setup`);
101+
if (this.isSetup) {
102+
this.logger.error(`is already setup`);
103+
return;
104+
}
105+
106+
this.logger.info(`setup react pages ${this.absPagesDir}`);
92107

93108
const pageFileNames = ensureArray(this.options.fileNames.page);
94109

95110
if (pageFileNames.length > 0) {
96111
const pageFiles = await glob(
97112
nodePath.join('**', pageFileNames.length > 1 ? `{${pageFileNames.join(',')}}` : pageFileNames[0]),
98113
{
99-
cwd: this.absApp,
114+
cwd: this.absPagesDir,
100115
nodir: true,
101116
dot: false,
102117
ignore: this.options.excludes,

Diff for: ‎packages/unplugin-react-pages/src/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export * from './const';
1+
export { pkgName, pkgVersion } from './const';
22
export { reactPages } from './plugin';

Diff for: ‎packages/unplugin-react-pages/src/plugin.ts

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { LogLevel, ModuleNode, Plugin } from 'vite';
22
import { pkgName } from './const';
3-
import { ReactApp } from './core/ReactApp';
3+
import { ReactPages } from './core/ReactPages';
44
import { type DeepPartial, withDefaults } from './helpers';
55
import type { FileType } from './core/FSTree';
66

@@ -14,7 +14,7 @@ export interface PluginOptions {
1414
* 应用目录
1515
* @default 'src/pages'
1616
*/
17-
appDir: string;
17+
pagesDir: string;
1818

1919
/**
2020
* 文件名映射
@@ -45,12 +45,12 @@ export interface PluginOptions {
4545
export type UserPluginOptions = DeepPartial<PluginOptions>;
4646

4747
// @ref https://cn.vitejs.dev/guide/api-plugin#virtual-modules-convention
48-
const virtualModuleId = 'virtual:react-app';
48+
const virtualModuleId = 'virtual:react-pages';
4949
const resolvedVirtualModuleId = `\0${virtualModuleId}`;
5050

5151
const defaultPluginOptions: () => PluginOptions = () => ({
5252
debug: false,
53-
appDir: 'src/pages',
53+
pagesDir: 'src/pages',
5454
logLevel: 'error',
5555
disableLazy: false,
5656
caseSensitive: false,
@@ -67,19 +67,19 @@ const defaultPluginOptions: () => PluginOptions = () => ({
6767
});
6868

6969
export function reactPages(userPluginOptions?: UserPluginOptions): Plugin {
70-
let reactApp: ReactApp | null = null;
70+
let reactPages: ReactPages | null = null;
7171

7272
return {
7373
name: pkgName,
7474
enforce: 'pre',
7575

7676
async configResolved(config) {
77-
reactApp = new ReactApp(withDefaults(defaultPluginOptions(), userPluginOptions), config);
77+
reactPages = new ReactPages(withDefaults(defaultPluginOptions(), userPluginOptions), config);
7878
},
7979

8080
async configureServer(server) {
81-
await reactApp?.connect(server, function () {
82-
this.logger.info(`react-app is changed`);
81+
await reactPages?.watch(server, function () {
82+
this.logger.info(`react-pages is changed`);
8383

8484
const { moduleGraph } = server;
8585
const mods = moduleGraph.getModulesByFile(resolvedVirtualModuleId);
@@ -108,7 +108,7 @@ export function reactPages(userPluginOptions?: UserPluginOptions): Plugin {
108108
if (id !== resolvedVirtualModuleId)
109109
return;
110110

111-
return reactApp?.output;
111+
return reactPages?.generate();
112112
},
113113
};
114114
}

0 commit comments

Comments
 (0)
Please sign in to comment.