CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tarojs--service

Core service layer for the Taro cross-platform framework providing plugin management, configuration handling, and platform abstraction capabilities

Pending
Overview
Eval results
Files

plugin-system.mddocs/

Plugin System & Kernel

Core orchestration system managing plugins, commands, platforms, and the complete build process through an event-driven architecture with comprehensive lifecycle hooks.

Capabilities

Kernel Class

Central orchestrator that manages the entire plugin system, commands, platforms, and build process lifecycle.

/**
 * Core kernel class extending EventEmitter for plugin orchestration
 */
class Kernel extends EventEmitter {
  appPath: string;
  plugins: Map<string, IPlugin>;
  platforms: Map<string, IPlatform>;
  commands: Map<string, ICommand>;
  hooks: Map<string, IHook[]>;
  methods: Map<string, Func[]>;
  paths: IPaths;
  config: Config;
  initialConfig: IProjectConfig;
  helper: any;
  runnerUtils: any;
  runOpts: any;

  constructor(options: IKernelOptions);
  run(args: string | { name: string; opts?: any }): Promise<void>;
  applyPlugins(args: string | { name: string; initialVal?: any; opts?: any }): Promise<any>;
  runWithPlatform(platform: string): TConfig;
  setRunOpts(opts: any): void;
  runHelp(name: string): void;
}

interface IKernelOptions {
  /** Application root path */
  appPath: string;
  /** Configuration instance */
  config: Config;
  /** List of presets to load */
  presets?: PluginItem[];
  /** List of plugins to load */
  plugins?: PluginItem[];
}

Usage Examples:

import { Kernel, Config } from "@tarojs/service";

// Create kernel with configuration
const config = new Config({ appPath: process.cwd() });
await config.init({ mode: 'development', command: 'build' });

const kernel = new Kernel({
  appPath: process.cwd(),
  config,
  plugins: [
    '@tarojs/plugin-react',
    ['@tarojs/plugin-sass', { /* options */ }]
  ]
});

// Run a build command
await kernel.run({
  name: 'build',
  opts: { 
    platform: 'weapp',
    watch: true 
  }
});

Command Execution

Execute registered commands with platform-specific configuration and options.

/**
 * Execute a registered command with optional configuration
 * @param args - Command name or object with name and options
 */
run(args: string | { name: string; opts?: any }): Promise<void>;

The run method orchestrates the complete command lifecycle:

  1. Initializes all presets and plugins
  2. Applies onReady and onStart hooks
  3. Validates command exists
  4. Configures platform-specific settings if specified
  5. Executes the command through plugin hooks

Usage Examples:

// Simple command execution
await kernel.run('build');

// Command with options
await kernel.run({
  name: 'build',
  opts: {
    platform: 'weapp',
    watch: true,
    options: { port: 3000 }
  }
});

Hook System

Execute registered hooks with waterfall pattern for data transformation and event handling.

/**
 * Apply registered hooks in waterfall pattern
 * @param args - Hook name or object with name, initial value, and options
 * @returns Promise resolving to final transformed value
 */
applyPlugins(args: string | { name: string; initialVal?: any; opts?: any }): Promise<any>;

Hook execution supports three patterns:

  • Modify hooks (modifyWebpackChain, modifyViteConfig): Transform and return values
  • Event hooks (onBuildStart, onBuildFinish): Execute side effects
  • Add hooks (addPluginOptsSchema): Collect multiple values into array

Usage Examples:

// Execute event hook
await kernel.applyPlugins('onBuildStart');

// Execute modify hook with initial value
const modifiedConfig = await kernel.applyPlugins({
  name: 'modifyWebpackChain',
  initialVal: webpackConfig,
  opts: { data: buildData }
});

Platform Configuration

Configure and execute builds with platform-specific settings.

/**
 * Configure kernel for specific platform execution
 * @param platform - Platform name to configure for
 * @returns Platform-specific configuration object
 */
runWithPlatform(platform: string): TConfig;

Configures the kernel with platform-specific settings and sets environment variables for the target platform.

Plugin Class

Base plugin class providing registration capabilities for hooks, commands, platforms, and methods.

/**
 * Base plugin class for registering hooks and capabilities
 */
class Plugin {
  id: string;
  path: string;
  ctx: Kernel;
  optsSchema: Func;

  constructor(opts: { id: string; path: string; ctx: Kernel });
  register(hook: IHook): void;
  registerCommand(command: ICommand): void;
  registerPlatform(platform: IPlatform): void;
  registerMethod(...args: any[]): void;
  addPluginOptsSchema(schema: Function): void;
}

Usage in Plugin Development:

// Plugin implementation
export default (ctx) => {
  // Register a build hook
  ctx.register({
    name: 'onBuildStart',
    fn: async (opts) => {
      console.log('Build starting...');
    }
  });

  // Register a webpack modification hook
  ctx.register({
    name: 'modifyWebpackChain',
    fn: (opts, { chain }) => {
      chain.plugin('MyPlugin')
        .use(MyWebpackPlugin, [options]);
      return { chain };
    }
  });

  // Register a custom command
  ctx.registerCommand({
    name: 'custom-build',
    fn: async (opts) => {
      // Custom build logic
    }
  });
};

Plugin Registration and Management

Internal methods for managing plugin lifecycle and registration.

/**
 * Initialize and register a single plugin
 * @param plugin - Plugin configuration object
 */
initPlugin(plugin: IPlugin): void;

/**
 * Initialize and register a preset (which can load additional plugins)
 * @param preset - Preset configuration object
 * @param isGlobalConfigPreset - Whether this preset is from global config
 */
initPreset(preset: IPreset, isGlobalConfigPreset?: boolean): void;

/**
 * Register a plugin in the kernel's plugin registry
 * @param plugin - Plugin to register
 */
registerPlugin(plugin: IPlugin): void;

Core Plugin Interfaces

interface IPlugin {
  /** Unique plugin identifier */
  id: string;
  /** Plugin file path */
  path: string;
  /** Plugin configuration options */
  opts: any;
  /** Plugin type (Plugin or Preset) */
  type: PluginType;
  /** Plugin apply function that returns the plugin implementation */
  apply: Func;
}

interface IHook {
  /** Hook name (e.g., 'onBuildStart', 'modifyWebpackChain') */
  name: string;
  /** Plugin ID that registered this hook */
  plugin?: string;
  /** Hook implementation function */
  fn: Func;
  /** Execute this hook before another hook */
  before?: string;
  /** Execution stage (lower numbers execute first) */
  stage?: number;
}

interface ICommand extends IHook {
  /** Command alias */
  alias?: string;
  /** CLI options mapping for help display */
  optionsMap?: Record<string, string>;
  /** Usage examples for help display */
  synopsisList?: string[];
}

interface IPlatform extends IHook {
  /** Configuration section name to use for this platform */
  useConfigName?: string;
}

enum PluginType {
  Preset = 'Preset',
  Plugin = 'Plugin'
}

Plugin Development Patterns

Basic Plugin Structure

export default (ctx) => {
  // Plugin initialization
  ctx.register({
    name: 'onBuildStart',
    fn: async (opts) => {
      // Build start logic
    }
  });
};

Plugin with Options Validation

export default (ctx, opts) => {
  // Add options schema validation
  ctx.addPluginOptsSchema((joi) => {
    return joi.object({
      outputDir: joi.string(),
      minify: joi.boolean().default(true)
    });
  });

  // Use validated options
  ctx.register({
    name: 'modifyWebpackChain',
    fn: (opts, { chain }) => {
      if (opts.minify) {
        // Add minification
      }
    }
  });
};

Preset Structure

export default (ctx, opts) => {
  return {
    presets: [
      // Additional presets to load
    ],
    plugins: [
      // Plugins to load
      '@tarojs/plugin-react',
      ['@tarojs/plugin-sass', { /* options */ }]
    ]
  };
};

Install with Tessl CLI

npx tessl i tessl/npm-tarojs--service

docs

configuration.md

index.md

platform-abstraction.md

plugin-context.md

plugin-system.md

tile.json