插件的 setup
函数会接收一个 api
入参,你可以调用 api 上提供的一些方法来获取到配置、应用上下文等信息。
import type { CliPlugin } from '@modern-js/core';
export const myPlugin = (): CliPlugin => ({
name: 'my-plugin',
setup(api) {
// 获取应用原始配置
const config = api.useConfigContext();
// 获取应用运行上下文
const appContext = api.useAppContext();
// 获取解析之后的最终配置
const resolvedConfig = api.useResolvedConfigContext();
},
});
用于获取应用原始配置。
const useConfigContext: () => UserConfig;
interface UserConfig {
source?: SourceConfig;
output?: OutputConfig;
server?: ServerConfig;
deploy?: DeployConfig;
// ...other fields
}
具体配置字段的意义请参考 配置。
该方法获取到的是只读配置,不可修改。如果需要修改配置,请使用 config hook。
用于获取被解析、合并之后的最终配置。
const useResolvedConfigContext: () => NormalizedConfig;
interface NormalizedConfig {
source: NormalizedSourceConfig;
output: NormalizedOutputConfig;
server: NormalizedServerConfig;
deploy: NormalizedDeployConfig;
_raw: UserConfig; // 原始配置对象
// ...other fields
}
配置字段的完整内容请参考 配置。
该方法获取到的是只读配置,不可修改。如果需要修改配置,请使用 config hook。
用于获取应用运行上下文。
const useAppContext: () => IAppContext;
interface IAppContext {
appDirectory: string;
configFile: string | false;
ip?: string;
port?: number;
distDirectory: string;
packageName: string;
srcDirectory: string;
sharedDirectory: string;
nodeModulesDirectory: string;
internalDirectory: string;
plugins: {
cli?: any;
server?: any;
}[];
entrypoints: Entrypoint[];
serverRoutes: ServerRoute[];
htmlTemplates: HtmlTemplates;
}
用于获取 Hooks 的执行器,并触发特定的 Hook 执行。
import type { CliPlugin } from '@modern-js/core';
export const myPlugin = (): CliPlugin => ({
name: 'my-plugin',
async setup(api) {
const hookRunners = api.useHookRunners();
// 触发 afterBuild Hook
await hookRunners.afterBuild();
},
});