Skip to content

Commit

Permalink
feat: support for plugin communication
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan committed Apr 1, 2024
1 parent b25e499 commit c36f0f4
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
38 changes: 38 additions & 0 deletions e2e/cases/javascript-api/plugin-expose/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { test, expect } from '@playwright/test';
import { type RsbuildPlugin, createRsbuild } from '@rsbuild/core';

type ParentAPI = {
initial: number;
double: (val: number) => number;
};

test('should allow plugin to expose and consume API', async () => {
const parentSymbol = Symbol('parent-api');

const pluginParent: RsbuildPlugin = {
name: 'plugin-parent',
setup(api) {
api.expose<ParentAPI>(parentSymbol, {
initial: 1,
double: (val: number) => val * 2,
});
},
};

const pluginChild: RsbuildPlugin = {
name: 'plugin-child',
setup(api) {
const parentAPI = api.useExposed<ParentAPI>(parentSymbol);
expect(parentAPI?.double(parentAPI.initial)).toEqual(2);
},
};

const rsbuild = await createRsbuild({
cwd: __dirname,
rsbuildConfig: {
plugins: [pluginParent, pluginChild],
},
});

await rsbuild.build();
});
1 change: 1 addition & 0 deletions e2e/cases/javascript-api/plugin-expose/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('1');
14 changes: 14 additions & 0 deletions packages/core/src/provider/initPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,26 @@ export function getPluginAPI({
);
};

const exposed: Array<{ id: string | symbol; api: any }> = [];

const expose = (id: string | symbol, api: any) => {
exposed.push({ id, api });
};
const useExposed = (id: string | symbol) => {
const matched = exposed.find((item) => item.id === id);
if (matched) {
return matched.api;
}
};

onExitProcess(() => {
hooks.onExit.call();
});

return {
context: publicContext,
expose,
useExposed,
getHTMLPaths,
getRsbuildConfig,
getNormalizedConfig,
Expand Down
6 changes: 6 additions & 0 deletions packages/shared/src/types/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,10 @@ export type RsbuildPluginAPI = {
getHTMLPaths: () => Record<string, string>;
getRsbuildConfig: GetRsbuildConfig;
getNormalizedConfig: () => NormalizedConfig;

/**
* For plugin communication
*/
expose: <T = any>(id: string | symbol, api: T) => void;
useExposed: <T = any>(id: string | symbol) => T | undefined;
};

0 comments on commit c36f0f4

Please sign in to comment.