插件 API

插件的 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();
  },
});

API

useConfigContext

用于获取应用原始配置。

const useConfigContext: () => UserConfig;

interface UserConfig {
  source?: SourceConfig;
  output?: OutputConfig;
  server?: ServerConfig;
  deploy?: DeployConfig;
  // ...other fields
}

具体配置字段的意义请参考 配置

TIP

该方法获取到的是只读配置,不可修改。如果需要修改配置,请使用 config hook

useResolvedConfigContext

用于获取被解析、合并之后的最终配置。

const useResolvedConfigContext: () => NormalizedConfig;

interface NormalizedConfig {
  source: NormalizedSourceConfig;
  output: NormalizedOutputConfig;
  server: NormalizedServerConfig;
  deploy: NormalizedDeployConfig;
  _raw: UserConfig; // 原始配置对象
  // ...other fields
}

配置字段的完整内容请参考 配置

TIP

该方法获取到的是只读配置,不可修改。如果需要修改配置,请使用 config hook

useAppContext

用于获取应用运行上下文。

const useAppContext: () => IAppContext;

interface IAppContext {
  /** 当前项目的根目录 */
  appDirectory: string;
  /** 源代码目录 */
  srcDirectory: string;
  /** 构建产出输出目录 */
  distDirectory: string;
  /** 公共模块目录 */
  sharedDirectory: string;
  /** 框架临时文件输出目录 */
  internalDirectory: string;
  /** node_modules 目录 */
  nodeModulesDirectory: string;
  /** 配置文件路径 */
  configFile: string | false;
  /** 当前机器的 IPv4 地址 */
  ip?: string;
  /** 开发服务器的端口号 */
  port?: number;
  /** 当前项目 package.json 的 name */
  packageName: string;
  /** 当前注册的插件 */
  plugins: any[];
  /** 页面入口信息 */
  entrypoints: Entrypoint[];
  /** 服务端路由信息 */
  serverRoutes: ServerRoute[];
  /** 当前项目类型 */
  toolsType?: 'app-tools' | 'module-tools' | 'monorepo-tools';
  /** 当前使用的打包工具类型 */
  bundlerType?: 'webpack' | 'rspack' | 'esbuild';
}
TIP

AppContext 中的部分字段是动态设置的,会随着程序的运行而变化。因此,当插件在不同的时机读取字段时,可能会获取到不同的值。

useHookRunners

用于获取 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();
  },
});
TIP

请尽量避免执行框架内置的 hooks,否则可能会导致框架内部的运行逻辑出错。