0
# Programmatic Usage
1
2
Plop can be embedded in custom CLI tools and workflows through its programmatic API, allowing you to wrap plop functionality in your own applications.
3
4
## Capabilities
5
6
### Core Execution
7
8
Main execution function for running plop generators programmatically.
9
10
```javascript { .api }
11
/**
12
* The main execution function for plop generators
13
* @param env - Environment object from Liftoff containing configuration
14
* @param _ - Unused parameter for compatibility (allows passArgsBeforeDashes to be explicit)
15
* @param passArgsBeforeDashes - Optional boolean to merge plop CLI API and generator API
16
* @returns Promise resolving to plop instance
17
*/
18
async function run(env, _, passArgsBeforeDashes);
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
import { Plop, run } from "plop";
25
26
// Standard execution
27
Plop.prepare({
28
cwd: process.cwd(),
29
configPath: './plopfile.js'
30
}, env => Plop.execute(env, run));
31
32
// With args merging enabled (passArgsBeforeDashes = true)
33
Plop.prepare({
34
cwd: process.cwd(),
35
configPath: './plopfile.js'
36
}, env => Plop.execute(env, (env) => run(env, undefined, true)));
37
38
// Complete example with error handling
39
Plop.prepare({
40
cwd: process.cwd(),
41
configPath: './plopfile.js'
42
}, async env => {
43
try {
44
const plopInstance = await Plop.execute(env, run);
45
console.log('Plop execution completed successfully');
46
} catch (error) {
47
console.error('Plop execution failed:', error.message);
48
process.exit(1);
49
}
50
});
51
```
52
53
### Liftoff Integration
54
55
Plop uses Liftoff for configuration file discovery and environment setup.
56
57
```javascript { .api }
58
/**
59
* Liftoff instance configured for plop
60
* Handles plopfile discovery and environment preparation
61
*/
62
const Plop: Liftoff;
63
```
64
65
**Configuration Properties:**
66
67
```javascript { .api }
68
interface LiftoffOptions {
69
name: string; // 'plop'
70
extensions: object; // JavaScript file variants from interpret
71
v8flags: string[]; // V8 flags for Node.js
72
}
73
```
74
75
**Usage Examples:**
76
77
```javascript
78
import { Plop } from "plop";
79
80
// Prepare plop environment
81
Plop.prepare({
82
cwd: process.cwd(),
83
configPath: '/path/to/plopfile.js',
84
preload: ['ts-node/register'],
85
completion: null
86
}, function(env) {
87
// Environment is ready, execute plop
88
Plop.execute(env, run);
89
});
90
```
91
92
### Progress Indication
93
94
Visual progress feedback during generator execution.
95
96
```javascript { .api }
97
/**
98
* Ora spinner instance for showing progress during file operations
99
*/
100
const progressSpinner: ora.Ora;
101
```
102
103
**Configuration:**
104
105
```javascript { .api }
106
interface ProgressSpinnerConfig {
107
stream: NodeJS.WriteStream; // stdout in test, stderr otherwise
108
isEnabled: boolean; // Disabled in test environment or with --no-progress
109
}
110
```
111
112
## Environment Configuration
113
114
### Liftoff Environment Object
115
116
The environment object passed to execution functions contains configuration paths and metadata (see LiftoffEnvironment type in main documentation).
117
118
### Preparation Options
119
120
Configuration options for Plop.prepare() (see PrepareOptions type in main documentation).
121
122
## Custom CLI Wrapper
123
124
Complete example of wrapping Plop in a custom CLI tool:
125
126
```javascript
127
#!/usr/bin/env node
128
import path from "node:path";
129
import minimist from "minimist";
130
import { Plop, run } from "plop";
131
import { dirname } from "node:path";
132
import { fileURLToPath } from "node:url";
133
134
const args = process.argv.slice(2);
135
const argv = minimist(args);
136
const __dirname = dirname(fileURLToPath(import.meta.url));
137
138
Plop.prepare({
139
cwd: argv.cwd,
140
configPath: path.join(__dirname, 'plopfile.js'),
141
preload: argv.preload || [],
142
completion: argv.completion
143
}, env => Plop.execute(env, run));
144
```
145
146
### Custom Destination Path
147
148
Override the destination path for generated files:
149
150
```javascript
151
Plop.prepare({
152
// config options
153
}, env =>
154
Plop.execute(env, (env) => {
155
const options = {
156
...env,
157
dest: process.cwd() // Base destination on current directory
158
}
159
return run(options, undefined, true)
160
})
161
)
162
```
163
164
## Error Handling
165
166
Programmatic usage should handle these error scenarios:
167
168
- **Plopfile not found**: `env.configPath` will be null
169
- **Generator execution errors**: Thrown from `run()` function
170
- **Node-plop errors**: Thrown during plop instance creation
171
- **Action failures**: May cause process exit depending on configuration
172
173
**Example Error Handling:**
174
175
```javascript
176
try {
177
const plop = await run(env);
178
console.log('Generation completed successfully');
179
} catch (error) {
180
console.error('Generation failed:', error.message);
181
process.exit(1);
182
}
183
```