Skip to content

Commit

Permalink
feat: umi devServer support custom express middleware hooks (umijs#9685)
Browse files Browse the repository at this point in the history
* feat: umi devServer support custom express middleware hooks

* feat: devServe remove onAfterMiddleware

Co-authored-by: chencheng (云谦) <[email protected]>
  • Loading branch information
xierenyuan and sorrycc authored Nov 3, 2022
1 parent 0e9783f commit eb463a1
Show file tree
Hide file tree
Showing 11 changed files with 53 additions and 4 deletions.
11 changes: 11 additions & 0 deletions docs/docs/api/plugin-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,17 @@ api.modifyWebpackConfig((memo, { webpack, env }) => {
### onBeforeCompiler
generate 之后,webpack / vite compiler 之前。传入的 fn 不接收任何参数。

### onBeforeMiddleware
提供在服务器内部执行所有其他中间件之前执行自定义中间件的能力, 这可以用来定义自定义处理程序, 例如:

```ts
api.onBeforeMiddleware(({ app }) => {
app.get('/some/path', function (req, res) {
res.json({ custom: 'response' });
});
});
```

### onBuildComplete
build 完成时。传入的 fn 接收 `{ isFirstCompile: boolean, stats, time: number, err?: Error }` 作为参数。

Expand Down
2 changes: 1 addition & 1 deletion examples/boilerplate-vue/.umirc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default {
crossorigin: {},
presets: [require.resolve('@umijs/preset-vue')],
polyfill: false,
// vite: {},
vite: {},
title: 'boilerplate - umi 4 & vue',
scripts: [
`/*alert(2);*/`,
Expand Down
9 changes: 8 additions & 1 deletion examples/boilerplate-vue/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IApi } from 'umi';
import type { IApi } from 'umi';

export default (api: IApi) => {
api.modifyHTML(($) => {
Expand Down Expand Up @@ -27,4 +27,11 @@ export default (api: IApi) => {
args;
// console.log('> onCheckCode', args);
});

api.onBeforeMiddleware(({ app }) => {
app.get('/some/path', function (req, res) {
res.json({ custom: 'response' });
});
console.log('> onBeforeMiddleware', typeof app);
});
};
2 changes: 2 additions & 0 deletions packages/bundler-vite/src/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ interface IOpts {
extraBabelPlugins?: IBabelPlugin[];
extraBabelPresets?: IBabelPlugin[];
modifyViteConfig?: Function;
onBeforeMiddleware?: Function;
}

export async function dev(opts: IOpts) {
Expand Down Expand Up @@ -44,5 +45,6 @@ export async function dev(opts: IOpts) {
beforeMiddlewares: opts.beforeMiddlewares,
afterMiddlewares: opts.afterMiddlewares,
onDevCompileDone: opts.onDevCompileDone,
onBeforeMiddleware: opts.onBeforeMiddleware,
});
}
5 changes: 5 additions & 0 deletions packages/bundler-vite/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ interface IOpts {
isFirstCompile: boolean;
stats: HmrContext['modules'] | DepOptimizationMetadata;
}) => Promise<void> | void;
onBeforeMiddleware?: Function;
}

export async function createServer(opts: IOpts) {
Expand Down Expand Up @@ -80,6 +81,10 @@ export async function createServer(opts: IOpts) {
// before middlewares
opts.beforeMiddlewares?.forEach((m) => app.use(m));

if (opts.onBeforeMiddleware) {
opts.onBeforeMiddleware(app);
}

// proxy
if (userConfig.proxy) {
createProxy(userConfig.proxy, app);
Expand Down
2 changes: 2 additions & 0 deletions packages/bundler-webpack/src/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type IOpts = {
mfsuInclude?: string[];
srcCodeCache?: any;
startBuildWorker?: (deps: any[]) => Worker;
onBeforeMiddleware?: Function;
} & Pick<IConfigOpts, 'cache' | 'pkg'>;

export function stripUndefined(obj: any) {
Expand Down Expand Up @@ -190,5 +191,6 @@ export async function dev(opts: IOpts) {
afterMiddlewares: [...(opts.afterMiddlewares || [])],
onDevCompileDone: opts.onDevCompileDone,
onProgress: opts.onProgress,
onBeforeMiddleware: opts.onBeforeMiddleware,
});
}
5 changes: 4 additions & 1 deletion packages/bundler-webpack/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import type webpack from '../compiled/webpack';
import './requireHook';

export type { RequestHandler } from '@umijs/bundler-utils/compiled/express';
export type {
RequestHandler,
Express,
} from '@umijs/bundler-utils/compiled/express';
export type { Compiler, Stats } from '../compiled/webpack';
export * from './build';
export * from './config/config';
Expand Down
6 changes: 6 additions & 0 deletions packages/bundler-webpack/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ interface IOpts {
afterMiddlewares?: any[];
onDevCompileDone?: Function;
onProgress?: Function;
onBeforeMiddleware?: Function;
}

export async function createServer(opts: IOpts) {
Expand Down Expand Up @@ -65,6 +66,11 @@ export async function createServer(opts: IOpts) {
// before middlewares
(opts.beforeMiddlewares || []).forEach((m) => app.use(m));

// Provides the ability to execute custom middleware prior to all other middleware internally within the server.
if (opts.onBeforeMiddleware) {
opts.onBeforeMiddleware(app);
}

// webpack dev middleware
const configs = Array.isArray(webpackConfig)
? webpackConfig
Expand Down
9 changes: 9 additions & 0 deletions packages/preset-umi/src/commands/dev/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ PORT=8888 umi dev
umi: join(api.paths.absTmpPath, 'umi.ts'),
},
});

const opts: any = {
config: api.config,
pkg: api.pkg,
Expand Down Expand Up @@ -349,6 +350,14 @@ PORT=8888 umi dev
...(api.config.mfsu?.include || []),
]),
startBuildWorker,
onBeforeMiddleware(app: any) {
api.applyPlugins({
key: 'onBeforeMiddleware',
args: {
app,
},
});
},
};

await api.applyPlugins({
Expand Down
1 change: 1 addition & 0 deletions packages/preset-umi/src/registerMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export default (api: IApi) => {
'onCheckPkgJSON',
'onCheckCode',
'onCheckConfig',
'onBeforeMiddleware',
'addBeforeMiddlewares',
'addLayouts',
'addMiddlewares',
Expand Down
5 changes: 4 additions & 1 deletion packages/preset-umi/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// sort-object-keys
import type { ImportDeclaration } from '@umijs/bundler-utils/compiled/@babel/types';
import type { RequestHandler, webpack } from '@umijs/bundler-webpack';
import type { RequestHandler, webpack, Express } from '@umijs/bundler-webpack';
import type WebpackChain from '@umijs/bundler-webpack/compiled/webpack-5-chain';
import type { IConfig } from '@umijs/bundler-webpack/dist/types';
import type {
Expand Down Expand Up @@ -132,6 +132,9 @@ export type IApi = PluginAPI &
}
>;
onBeforeCompiler: IEvent<{ compiler: 'vite' | 'webpack'; opts: any }>;
onBeforeMiddleware: IEvent<{
app: Express;
}>;
onBuildComplete: IEvent<{
err?: Error;
isFirstCompile: boolean;
Expand Down

0 comments on commit eb463a1

Please sign in to comment.