Enhanced development experience with logging utilities, output formatting, platform detection, update checking, and developer workflow optimizations for uni-app development.
Comprehensive logging with message deduplication and type-specific output management.
/**
* Resets output state for given log type, clearing previous messages
* @param type - Type of log output to reset
*/
function resetOutput(type: LogType): void;
/**
* Outputs message with automatic deduplication to prevent spam
* @param type - Type of log message
* @param msg - Message content to output
*/
function output(type: LogType, msg: string): void;
/**
* Log message types supported by the output system
*/
type LogType = 'error' | 'warn' | 'info' | 'log';Usage Example:
import { output, resetOutput, type LogType } from "@dcloudio/uni-cli-shared";
// Basic logging with deduplication
output('info', 'Build process started');
output('info', 'Build process started'); // Won't log again due to deduplication
// Log different message types
output('warn', 'Deprecated API usage detected in component');
output('error', 'Failed to compile UTS module');
output('log', 'Debug information for troubleshooting');
// Reset specific log type
resetOutput('error'); // Clear all previous error messages
output('error', 'This error will be shown even if logged before');
// Development workflow example
function developmentLogger() {
return {
logBuildStep(step: string) {
output('info', `[BUILD] ${step}`);
},
logWarning(component: string, warning: string) {
output('warn', `[${component}] ${warning}`);
},
logError(error: Error) {
output('error', `Build failed: ${error.message}`);
},
resetLogs() {
(['error', 'warn', 'info', 'log'] as LogType[]).forEach(resetOutput);
}
};
}Utilities for formatting different types of log messages with consistent styling.
/**
* Formats error messages with appropriate styling and context
* @returns Formatted error message function
*/
function formatErrMsg(): (msg: string) => string;
/**
* Formats informational messages for user display
* @returns Formatted info message function
*/
function formatInfoMsg(): (msg: string) => string;
/**
* Formats warning messages with visual indicators
* @returns Formatted warning message function
*/
function formatWarnMsg(): (msg: string) => string;Usage Example:
import {
formatErrMsg,
formatInfoMsg,
formatWarnMsg
} from "@dcloudio/uni-cli-shared";
// Initialize message formatters
const formatError = formatErrMsg();
const formatInfo = formatInfoMsg();
const formatWarning = formatWarnMsg();
// Format different message types
const errorMessage = formatError('Component compilation failed');
const infoMessage = formatInfo('Successfully built for H5 platform');
const warningMessage = formatWarning('API will be deprecated in next version');
console.log(errorMessage); // ❌ Component compilation failed
console.log(infoMessage); // ✅ Successfully built for H5 platform
console.log(warningMessage); // ⚠️ API will be deprecated in next version
// Integration with build system
class BuildReporter {
private formatError = formatErrMsg();
private formatInfo = formatInfoMsg();
private formatWarning = formatWarnMsg();
reportSuccess(platform: string, duration: number) {
console.log(
this.formatInfo(`Build completed for ${platform} in ${duration}ms`)
);
}
reportWarning(file: string, issue: string) {
console.log(
this.formatWarning(`${file}: ${issue}`)
);
}
reportError(error: Error) {
console.log(
this.formatError(`Build failed: ${error.message}`)
);
}
}Automated CLI update detection and notification system.
/**
* Checks for CLI updates and notifies users of available versions
* @param options - Update checking configuration options
* @returns Promise that resolves when check is complete
*/
function checkUpdate(options: CheckUpdateOptions): Promise<void>;
interface CheckUpdateOptions {
/** Input directory path */
inputDir: string;
/** Compiler version to check */
compilerVersion: string;
/** Version type identifier */
versionType?: string;
}Usage Example:
import { checkUpdate } from "@dcloudio/uni-cli-shared";
// Basic update check
await checkUpdate({
inputDir: process.cwd(),
compilerVersion: '3.0.0-alpha-4080120250820001'
});
// Custom update check with options
await checkUpdate({
inputDir: './my-uni-app',
compilerVersion: '3.0.0',
versionType: 'cli'
});
// Integration in CLI tool
async function initializeCLI() {
console.log('Starting uni-app CLI...');
// Check for updates in background
checkUpdate({
inputDir: process.cwd(),
compilerVersion: process.env.UNI_CLI_VERSION || '3.0.0'
}).catch(err => {
console.warn('Update check failed:', err.message);
});
// Continue with CLI operations
await startDevelopmentServer();
}
// Scheduled update checking
setInterval(async () => {
try {
await checkUpdate({
inputDir: process.cwd(),
compilerVersion: process.env.UNI_CLI_VERSION || '3.0.0'
});
} catch (error) {
// Silent failure for background checks
}
}, 24 * 60 * 60 * 1000); // Check dailyEnhanced IDE integration utilities for HBuilderX development environment.
/**
* Formats file paths for HBuilderX IDE display and navigation
* @returns Filename formatting function for IDE integration
*/
function formatAtFilename(): (filename: string) => string;
/**
* Initializes module aliases for HBuilderX project configuration
* @returns Module alias configuration
*/
function initModuleAlias(): Record<string, string>;
/**
* Installs HBuilderX plugin with proper configuration
* @returns Plugin installation result
*/
function installHBuilderXPlugin(): boolean;
/**
* Formats installation tips and guidance for HBuilderX plugins
* @returns Formatted installation instructions
*/
function formatInstallHBuilderXPluginTips(): string;Usage Example:
import {
formatAtFilename,
initModuleAlias,
installHBuilderXPlugin,
formatInstallHBuilderXPluginTips
} from "@dcloudio/uni-cli-shared";
// Initialize HBuilderX integration
const formatFilename = formatAtFilename();
const moduleAliases = initModuleAlias();
// Format file paths for IDE
const displayPath = formatFilename('/src/pages/index/index.vue');
console.log('IDE Path:', displayPath); // @/pages/index/index.vue
// Configure module aliases
console.log('Module aliases:', moduleAliases);
// { '@': './src', '@/components': './src/components' }
// Plugin installation workflow
if (!installHBuilderXPlugin()) {
const installTips = formatInstallHBuilderXPluginTips();
console.log(installTips);
}
// HBuilderX project setup
class HBuilderXIntegration {
setupProject(projectPath: string) {
// Initialize module aliases
const aliases = initModuleAlias();
// Create HBuilderX configuration
const config = {
name: 'uni-app-project',
type: 'uni-app',
moduleAliases: aliases,
plugins: []
};
// Attempt plugin installation
const pluginInstalled = installHBuilderXPlugin();
if (!pluginInstalled) {
const tips = formatInstallHBuilderXPluginTips();
this.showInstallationGuide(tips);
}
return config;
}
showInstallationGuide(tips: string) {
console.log('\n📦 HBuilderX Plugin Installation:');
console.log(tips);
}
}Utilities for detecting the current development platform and environment.
/**
* Platform detection flag for Windows systems
*/
const isWindows: boolean;Usage Example:
import { isWindows } from "@dcloudio/uni-cli-shared";
// Platform-specific configuration
const shellCommand = isWindows ? 'cmd /c' : 'sh -c';
const pathSeparator = isWindows ? '\\' : '/';
const executable = isWindows ? 'node.exe' : 'node';
// Cross-platform path handling
function buildPath(...segments: string[]): string {
return segments.join(pathSeparator);
}
// Platform-specific build commands
const buildCommands = {
install: isWindows ? 'npm.cmd install' : 'npm install',
build: isWindows ? 'npm.cmd run build' : 'npm run build',
dev: isWindows ? 'npm.cmd run dev' : 'npm run dev'
};
// Environment setup
function setupDevelopmentEnvironment() {
if (isWindows) {
// Windows-specific setup
process.env.FORCE_COLOR = '1';
process.env.NPM_CONFIG_SCRIPT_SHELL = 'cmd';
} else {
// Unix-like systems setup
process.env.SHELL = process.env.SHELL || '/bin/bash';
}
}Localized messages for development tools and error reporting.
/**
* Localized messages object with language-specific strings
* Automatically selects appropriate language based on system locale
*/
const M: Record<string, string>;Usage Example:
import { M } from "@dcloudio/uni-cli-shared";
// Access localized messages
console.log(M.BUILD_SUCCESS); // "构建成功" (Chinese) or "Build successful" (English)
console.log(M.BUILD_FAILED); // "构建失败" (Chinese) or "Build failed" (English)
console.log(M.UPDATING_DEPS); // "更新依赖中..." (Chinese) or "Updating dependencies..." (English)
// Use in development tools
class LocalizedReporter {
reportBuildStatus(success: boolean, platform: string) {
if (success) {
console.log(`${M.BUILD_SUCCESS} - ${platform}`);
} else {
console.log(`${M.BUILD_FAILED} - ${platform}`);
}
}
reportProgress(step: string) {
console.log(`${M.PROCESSING}: ${step}`);
}
}
// Error message localization
function showLocalizedError(errorCode: string, details?: string) {
const message = M[errorCode] || M.UNKNOWN_ERROR;
console.error(details ? `${message}: ${details}` : message);
}Re-exported development utilities from essential packages.
/**
* File watcher library for development server and hot reload
*/
import chokidar from "chokidar";Usage Example:
import chokidar from "@dcloudio/uni-cli-shared";
import { output } from "@dcloudio/uni-cli-shared";
// File watching for development
const watcher = chokidar.watch(['src/**/*.vue', 'src/**/*.js'], {
ignored: /node_modules/,
persistent: true
});
watcher
.on('change', (path) => {
output('info', `File changed: ${path}`);
// Trigger rebuild or hot reload
})
.on('add', (path) => {
output('info', `File added: ${path}`);
})
.on('unlink', (path) => {
output('warn', `File removed: ${path}`);
});
// Development server integration
class DevelopmentServer {
private watcher: any;
start() {
this.watcher = chokidar.watch('src/**/*', {
ignoreInitial: true
});
this.watcher.on('all', (event: string, path: string) => {
output('log', `[${event}] ${path}`);
this.handleFileChange(event, path);
});
}
stop() {
if (this.watcher) {
this.watcher.close();
}
}
private handleFileChange(event: string, path: string) {
// Implement hot reload logic
}
}Development tools provide a comprehensive suite of utilities for enhanced developer experience, consistent logging, platform compatibility, and seamless IDE integration across the uni-app development ecosystem.