This document provides detailed API documentation for the Catalyst React Plugin's internal architecture.
- Build Tool Detector
- Adapter Interface
- Vite Adapter
- Webpack Adapter
- Environment Configuration
- Error Handling
Detects which build tool (Vite or Webpack) a project is using.
new BuildToolDetector(userDir)Parameters:
userDir(string): Absolute path to the user's project directory
Example:
const detector = new BuildToolDetector('/path/to/project');Detects the build tool being used in the project.
Returns: string - Either 'vite' or 'webpack'
Throws: Error if no supported build tool is detected
Detection Priority:
- Vite (highest priority)
vitein dependencies/devDependenciesvite.config.js,vite.config.ts, orvite.config.mjsexists
- Webpack
webpackorreact-scriptsin dependencies/devDependencieswebpack.config.jsexists
Example:
const buildTool = detector.detect();
console.log(buildTool); // 'vite' or 'webpack'Gets detailed information about the detected build tool.
Returns: Object
{
buildTool: string, // 'vite' or 'webpack'
hasConfigFile: boolean, // Whether a config file exists
configFilePath: string, // Path to config file (if exists)
version: string // Version from package.json (if available)
}Example:
const details = detector.getDetails();
console.log(details);
// {
// buildTool: 'vite',
// hasConfigFile: true,
// configFilePath: '/path/to/project/vite.config.js',
// version: '^5.0.0'
// }Base class that defines the interface for build tool adapters.
new BaseBuildAdapter(userDir, paths)Parameters:
userDir(string): Absolute path to the user's project directorypaths(Object): Paths configuration object
All adapters must implement these methods:
Returns the name of the build tool.
Returns: string
Validates the project structure and dependencies.
Parameters:
command(string): The command being executed ('build' or 'serve')cliVersion(string, optional): Version of the Catalyst CLI
Returns: Promise<boolean>
Throws: Error if validation fails
Creates an optimized production build.
Parameters:
packageJsonFile(string): Absolute path to package.json
Returns: Promise<string> - Path to build output directory
Throws: Error if build fails
Starts the development server.
Parameters:
httpPort(number): Port for the development servermasterPort(number): Master port for URL constructionwatchMode(boolean): Whether to enable file watching
Returns: Promise<Object>
{
eventListener: EventEmitter, // Emits 'start' event when ready
urls: {
localUrlForBrowser: string, // URL to open in browser
localUrlForTerminal: string // URL to display in terminal
}
}Adapter for Vite-based React projects.
The validate() method performs these checks:
- Vite Installation: Checks for
node_modules/vite - Required Files:
index.html(at project root)- Entry point:
src/main.tsx,src/main.jsx,src/index.tsx, orsrc/index.jsx
- React Version: Must be >= 16.10.0
- CLI Version: Must be >= 1.13.2 (if provided)
- Vite Config: Detects
vite.config.jsorvite.config.ts
The build() method:
- Loads environment variables from
.envfiles - Cleans the build output directory
- Spawns
npx vite buildprocess - Monitors build output for errors
- Validates build output (checks for
index.html) - Measures and reports file sizes
- Copies
package.jsonto build directory - Returns build output path
Environment Variables:
- Uses
VITE_prefix - Automatically loads
.env,.env.local,.env.production, etc.
The start() method:
- Loads environment variables
- Spawns
npx vite --port <port> --hostprocess - Monitors stdout for server ready message
- Prepares URLs with master port replacement
- Emits 'start' event when ready
- Handles graceful shutdown on close signal
Example:
const adapter = new ViteAdapter('/path/to/project', paths);
// Validate
await adapter.validate('build', '1.13.2');
// Build
const buildPath = await adapter.build('/path/to/package.json');
// Start dev server
const { eventListener, urls } = await adapter.start(3000, 9000, true);
eventListener.on('start', () => {
console.log('Server ready at:', urls.localUrlForBrowser);
});Adapter for Webpack-based React projects (Create React App).
The Webpack adapter delegates all operations to existing modules:
validate()→lib/validate/index.jsbuild()→lib/build/index.jsstart()→lib/start/index.js
This ensures 100% backward compatibility with existing Webpack projects.
Example:
const adapter = new WebpackAdapter('/path/to/project', paths);
// All methods delegate to existing implementations
await adapter.validate('build', '1.13.2');
const buildPath = await adapter.build('/path/to/package.json');
const { eventListener, urls } = await adapter.start(3000, 9000, true);Gets environment variables filtered by build tool.
Location: lib/config/env.js
Parameters:
publicUrl(string): The public URL for the applicationbuildTool(string, optional):'webpack'or'vite'(defaults to'webpack')
Returns: Object
{
raw: {
NODE_ENV: string,
PUBLIC_URL: string,
// ... filtered environment variables
},
stringified: {
'process.env': {
NODE_ENV: '"production"',
PUBLIC_URL: '"/app"',
// ... stringified variables
}
}
}Environment Variable Prefixes:
- Webpack:
REACT_APP_prefix - Vite:
VITE_prefix
Example:
// For Webpack projects
const env = getClientEnvironment('/app', 'webpack');
// Includes: REACT_APP_API_URL, REACT_APP_ENV, etc.
// For Vite projects
const env = getClientEnvironment('/app', 'vite');
// Includes: VITE_API_URL, VITE_ENV, etc.Both build tools support:
.env- Default variables.env.local- Local overrides (gitignored).env.[mode]- Mode-specific (e.g.,.env.production).env.[mode].local- Mode-specific local overrides
Priority: More specific files override less specific ones.
Custom error class for plugin-specific errors.
Location: lib/utils/plugin-error.js
new PluginError(message, category, details)Parameters:
message(string): Error messagecategory(string): Error category fromErrorCategorydetails(Object, optional):suggestion(string): Suggested fixbuildTool(string): Build tool being usedoriginalError(Error): Original error if wrapping
const ErrorCategory = {
VALIDATION: 'VALIDATION',
BUILD: 'BUILD',
DEV_SERVER: 'DEV_SERVER',
CONFIGURATION: 'CONFIGURATION',
DEPENDENCY: 'DEPENDENCY'
};Formats the error with ANSI colors and suggestions.
Returns: string - Formatted error message
Example:
const { PluginError, ErrorCategory } = require('./lib/utils/plugin-error');
const error = new PluginError(
'Vite is not installed',
ErrorCategory.DEPENDENCY,
{
suggestion: 'Run: npm install vite @vitejs/plugin-react --save-dev',
buildTool: 'vite'
}
);
console.log(error.format());
// [DEPENDENCY] Vite is not installed
// Build tool: vite
//
// Suggestion:
// Run: npm install vite @vitejs/plugin-react --save-devGenerates path configuration for the project.
Location: lib/config/paths.js
Parameters:
userDir(string): User's project directory
Returns: Object - Paths configuration
Vite-Specific Paths:
- Entry point:
src/main.tsxorsrc/main.jsx(falls back tosrc/index.*) - HTML:
index.htmlat project root - Build output:
builddirectory
Webpack-Specific Paths:
- Entry point:
src/index.tsxorsrc/index.jsx - HTML:
public/index.html - Build output:
builddirectory
Example:
const paths = require('./lib/config/paths');
const projectPaths = paths('/path/to/project');
console.log(projectPaths.appIndexJs); // Entry point
console.log(projectPaths.appHtml); // HTML file
console.log(projectPaths.appBuild); // Build outputComplete example of using the plugin API:
const BuildToolDetector = require('./lib/detector/build-tool-detector');
const ViteAdapter = require('./lib/adapters/vite-adapter');
const WebpackAdapter = require('./lib/adapters/webpack-adapter');
const paths = require('./lib/config/paths');
async function buildProject(projectDir) {
// Detect build tool
const detector = new BuildToolDetector(projectDir);
const buildTool = detector.detect();
console.log(`Detected: ${buildTool}`);
// Get paths
const projectPaths = paths(projectDir);
// Create appropriate adapter
const Adapter = buildTool === 'vite' ? ViteAdapter : WebpackAdapter;
const adapter = new Adapter(projectDir, projectPaths);
// Validate
await adapter.validate('build', '1.13.2');
// Build
const buildPath = await adapter.build(projectPaths.appPackageJson);
console.log(`Build complete: ${buildPath}`);
return buildPath;
}Create vite.config.js in your project root:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
open: true
},
build: {
outDir: 'build',
sourcemap: true
}
});For Webpack projects using Create React App, configuration is managed by react-scripts. For custom Webpack configurations, create webpack.config.js.
-
Always validate before building or starting
await adapter.validate('build', cliVersion); await adapter.build(packageJsonFile);
-
Handle errors gracefully
try { await adapter.build(packageJsonFile); } catch (error) { if (error instanceof PluginError) { console.error(error.format()); } else { console.error(error.message); } }
-
Use the detector for automatic tool selection
const detector = new BuildToolDetector(userDir); const buildTool = detector.detect(); // Automatically use the right adapter
-
Respect environment variable prefixes
- Use
VITE_for Vite projects - Use
REACT_APP_for Webpack projects
- Use
For issues or questions:
- Check the Build Tool Detection guide
- Review the Migration Guide
- Open an issue on the repository