or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mddiagnostics.mdindex.mdpage-creation.mdplugin-development.mdproject-creation.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Core utility functions for path resolution, package management, file operations, and development helpers.

3

4

## Capabilities

5

6

### Path and Version Utilities

7

8

Essential utilities for path resolution and version management within the Taro CLI ecosystem.

9

10

```typescript { .api }

11

/**

12

* Get the root path of the Taro CLI package

13

* @returns Absolute path to CLI package root directory

14

*/

15

function getRootPath(): string;

16

17

/**

18

* Get the current version of the Taro CLI package

19

* @returns Version string from package.json

20

*/

21

function getPkgVersion(): string;

22

23

/**

24

* Get a specific field from the CLI package.json

25

* @param key - Package.json field key to retrieve

26

* @returns Field value or empty object if key doesn't exist

27

*/

28

function getPkgItemByKey(key: string): any;

29

30

/**

31

* Print the Taro CLI version to console with emoji

32

*/

33

function printPkgVersion(): void;

34

```

35

36

**Usage Examples:**

37

38

```typescript

39

import { getRootPath, getPkgVersion, getPkgItemByKey } from "@tarojs/cli";

40

41

// Get CLI root path

42

const cliRoot = getRootPath();

43

console.log(cliRoot); // /path/to/node_modules/@tarojs/cli

44

45

// Get CLI version

46

const version = getPkgVersion();

47

console.log(version); // "4.1.6"

48

49

// Get package dependencies

50

const deps = getPkgItemByKey('dependencies');

51

console.log(deps); // { "@tarojs/service": "...", ... }

52

53

// Print version with formatting

54

printPkgVersion(); // 👽 Taro v4.1.6

55

```

56

57

### File System Utilities

58

59

Comprehensive file system operations for directory traversal and file management.

60

61

```typescript { .api }

62

/**

63

* Get all files in a folder recursively with optional filtering

64

* @param folder - Directory path to scan

65

* @param filter - Optional array of filenames to exclude

66

* @returns Promise resolving to array of file paths

67

*/

68

function getAllFilesInFolder(

69

folder: string,

70

filter?: string[]

71

): Promise<string[]>;

72

73

/**

74

* File stat information interface

75

*/

76

interface FileStat {

77

/** File or directory name */

78

name: string;

79

/** Whether item is a directory */

80

isDirectory: boolean;

81

/** Whether item is a file */

82

isFile: boolean;

83

}

84

85

/**

86

* Read directory contents with file type information

87

* @param folder - Directory path to read

88

* @returns Array of file stat objects

89

*/

90

function readDirWithFileTypes(folder: string): FileStat[];

91

```

92

93

**Usage Examples:**

94

95

```typescript

96

import { getAllFilesInFolder, readDirWithFileTypes } from "@tarojs/cli";

97

98

// Get all files recursively

99

const allFiles = await getAllFilesInFolder('./src');

100

console.log(allFiles); // ['/src/app.tsx', '/src/pages/index.tsx', ...]

101

102

// Get files excluding certain patterns

103

const filteredFiles = await getAllFilesInFolder('./src', ['.DS_Store', 'Thumbs.db']);

104

105

// Read directory with file types

106

const dirContents = readDirWithFileTypes('./src');

107

dirContents.forEach(item => {

108

console.log(`${item.name}: ${item.isDirectory ? 'DIR' : 'FILE'}`);

109

});

110

```

111

112

### Template and Source Utilities

113

114

Utilities for handling template sources and determining template types.

115

116

```typescript { .api }

117

/**

118

* Template source type enumeration

119

*/

120

type TemplateSourceType = 'git' | 'url';

121

122

/**

123

* Determine the type of template source from URL

124

* @param url - Template URL or reference string

125

* @returns Template source type

126

*/

127

function getTemplateSourceType(url: string): TemplateSourceType;

128

```

129

130

**Usage Examples:**

131

132

```typescript

133

import { getTemplateSourceType } from "@tarojs/cli";

134

135

// Git-based templates

136

getTemplateSourceType('github:user/repo'); // 'git'

137

getTemplateSourceType('gitlab:user/repo'); // 'git'

138

getTemplateSourceType('direct:https://github.com/user/repo.git'); // 'git'

139

140

// URL-based templates

141

getTemplateSourceType('https://example.com/template.zip'); // 'url'

142

getTemplateSourceType('/local/path/template'); // 'url'

143

```

144

145

### Development and Console Utilities

146

147

Helper functions for development workflow and console interaction.

148

149

```typescript { .api }

150

/**

151

* Print development tips for specific platforms

152

* @param platform - Target platform name

153

*/

154

function printDevelopmentTip(platform: string): void;

155

156

/**

157

* Clear the console output

158

*/

159

function clearConsole(): void;

160

161

/**

162

* Execute shell command with callbacks for output handling

163

* @param params - Command execution parameters

164

*/

165

function execCommand(params: {

166

/** Command to execute */

167

command: string;

168

/** Callback for successful output */

169

successCallback?: (data: string) => void;

170

/** Callback for error output */

171

failCallback?: (data: string) => void;

172

}): void;

173

```

174

175

**Usage Examples:**

176

177

```typescript

178

import { printDevelopmentTip, clearConsole, execCommand } from "@tarojs/cli";

179

180

// Print platform-specific development tips

181

printDevelopmentTip('weapp');

182

// Output: Tips: 预览模式生成的文件较大,设置 NODE_ENV 为 production 可以开启压缩...

183

184

// Clear console for better UX

185

clearConsole();

186

187

// Execute command with output handling

188

execCommand({

189

command: 'npm install',

190

successCallback: (data) => console.log('Install output:', data),

191

failCallback: (error) => console.error('Install error:', error)

192

});

193

```

194

195

### Package Management Utilities

196

197

Utilities for package name handling and validation.

198

199

```typescript { .api }

200

/**

201

* Extract package name by removing version suffix

202

* @param pkgString - Package string with possible version

203

* @returns Package name without version

204

*/

205

function getPkgNameByFilterVersion(pkgString: string): string;

206

207

/**

208

* Check if value is null or undefined

209

* @param value - Value to check

210

* @returns True if value is null or undefined

211

*/

212

function isNil(value: any): value is null | undefined;

213

```

214

215

**Usage Examples:**

216

217

```typescript

218

import { getPkgNameByFilterVersion, isNil } from "@tarojs/cli";

219

220

// Extract package names

221

getPkgNameByFilterVersion('@tarojs/cli@4.1.6'); // '@tarojs/cli'

222

getPkgNameByFilterVersion('react@18.0.0'); // 'react'

223

getPkgNameByFilterVersion('@scoped/package'); // '@scoped/package'

224

225

// Null/undefined checking

226

isNil(null); // true

227

isNil(undefined); // true

228

isNil(0); // false

229

isNil(''); // false

230

isNil(false); // false

231

```

232

233

### Creator Base Class

234

235

Base class for template creation and project scaffolding functionality.

236

237

```typescript { .api }

238

/**

239

* Base creator class for template and project scaffolding

240

*/

241

class Creator {

242

protected _rootPath: string;

243

public rootPath: string;

244

245

/**

246

* Initialize creator with optional source root

247

* @param sourceRoot - Optional source root path

248

*/

249

constructor(sourceRoot?: string);

250

251

/**

252

* Initialize creator instance (override in subclasses)

253

*/

254

init(): void;

255

256

/**

257

* Set or get the source root path

258

* @param rootPath - Optional root path to set

259

* @returns Current root path

260

*/

261

sourceRoot(rootPath?: string): string;

262

263

/**

264

* Get template file path relative to templates directory

265

* @param args - Path segments to join

266

* @returns Complete template file path

267

*/

268

templatePath(...args: string[]): string;

269

270

/**

271

* Write template files (override in subclasses)

272

*/

273

write(): void;

274

}

275

```

276

277

**Usage Examples:**

278

279

```typescript

280

import { Creator } from "@tarojs/cli";

281

282

// Create custom creator

283

class CustomCreator extends Creator {

284

init() {

285

console.log('Initializing custom creator');

286

}

287

288

write() {

289

const templatePath = this.templatePath('custom', 'template.js');

290

// Write template files...

291

}

292

}

293

294

// Use creator

295

const creator = new CustomCreator('/custom/root');

296

creator.init();

297

298

// Get template paths

299

const jsTemplate = creator.templatePath('javascript', 'component.js');

300

const vueTemplate = creator.templatePath('vue', 'component.vue');

301

```

302

303

### Environment and System Utilities

304

305

Utilities for environment detection and system interaction.

306

307

```typescript { .api }

308

/**

309

* Common system and environment checking utilities

310

*/

311

interface SystemUtilities {

312

/** Check if running on Windows */

313

isWindows: boolean;

314

/** Get user home directory */

315

getUserHomeDir(): string;

316

/** Check Node.js version compatibility */

317

checkNodeVersion(required: string): boolean;

318

/** Detect package manager in project */

319

detectPackageManager(projectPath: string): NpmType;

320

}

321

322

/**

323

* Command execution utilities for cross-platform compatibility

324

*/

325

interface CommandUtilities {

326

/** Get appropriate command for platform */

327

getPlatformCommand(command: string): string;

328

/** Execute command with platform-specific handling */

329

executePlatformCommand(command: string): Promise<string>;

330

/** Build command with proper escaping */

331

buildCommand(cmd: string, args: string[]): string;

332

}

333

```

334

335

### Error Handling Utilities

336

337

Common error handling patterns and utilities for CLI operations.

338

339

```typescript { .api }

340

/**

341

* Common CLI error types

342

*/

343

type CLIErrorType =

344

| 'FILE_NOT_FOUND'

345

| 'PERMISSION_DENIED'

346

| 'INVALID_CONFIG'

347

| 'NETWORK_ERROR'

348

| 'TEMPLATE_ERROR'

349

| 'BUILD_ERROR';

350

351

/**

352

* CLI error class with context information

353

*/

354

class CLIError extends Error {

355

code: CLIErrorType;

356

context?: any;

357

358

constructor(message: string, code: CLIErrorType, context?: any);

359

}

360

361

/**

362

* Error handling utilities

363

*/

364

interface ErrorUtilities {

365

/** Handle and format errors for console output */

366

handleError(error: Error): void;

367

/** Create user-friendly error messages */

368

formatError(error: CLIError): string;

369

/** Log error with context */

370

logError(error: Error, context?: any): void;

371

}

372

```