### Custom Action Function Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/02-built-in-actions.md Demonstrates a custom action function that executes 'npm install' and returns a success message. Custom actions can perform any asynchronous operation and must return a string message on success or a rejected promise on failure. ```javascript plop.setGenerator('install', { prompts: [], actions: [ // Custom function to run npm install async (answers, config, plop) => { const { exec } = require('child_process'); return new Promise((resolve, reject) => { exec('npm install', (error, stdout) => { if (error) reject(error); else resolve('npm install completed'); }); }); }, // Built-in action { type: 'add', path: '.env', template: 'NODE_ENV=development' } ] }); ``` -------------------------------- ### Install Plop Globally Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Install Plop globally to use the 'plop' command from any directory. This is the recommended installation method. ```bash npm install -g plop ``` -------------------------------- ### Install Plop.js Globally Source: https://github.com/plopjs/plop/blob/main/README.md Install Plop.js globally for easy access from the command line. This is optional but recommended. ```bash $ npm install -g plop ``` -------------------------------- ### Confirm Prompt Bypass Examples Source: https://github.com/plopjs/plop/blob/main/_autodocs/06-prompt-bypass.md Examples demonstrating how to bypass 'confirm' prompts using 'yes' or 'no' keywords. These map to boolean true/false values. ```bash plop component "MyComp" yes // First: input, Second: true ``` ```bash plop component "MyComp" no // First: input, Second: false ``` -------------------------------- ### Install Plop.js Locally Source: https://github.com/plopjs/plop/blob/main/README.md Install Plop.js as a development dependency in your project. ```bash $ npm install --save-dev plop ``` -------------------------------- ### Configuration and Utility Methods Source: https://github.com/plopjs/plop/blob/main/README.md Methods for setting and getting Plop configuration, and rendering strings. ```APIDOC ## setWelcomeMessage ### Description Customizes the welcome message displayed when running `plop` to prompt for generator selection. ### Method setWelcomeMessage ### Parameters #### Path Parameters - **message** (String) - Required - The custom welcome message. ``` ```APIDOC ## setPlopfilePath ### Description Sets the internal `plopfilePath` value, which is used to locate resources like template files. ### Method setPlopfilePath ### Parameters #### Path Parameters - **path** (String) - Required - The absolute path to the plopfile. ``` ```APIDOC ## getPlopfilePath ### Description Returns the absolute path to the currently used plopfile. ### Method getPlopfilePath ### Returns - **String** - The absolute path to the plopfile. ``` ```APIDOC ## getDestBasePath ### Description Returns the base path that is used when creating files. ### Method getDestBasePath ### Returns - **String** - The base destination path. ``` ```APIDOC ## setDefaultInclude ### Description Sets the default configuration to be used if this plopfile is consumed by another plopfile using `plop.load()`. ### Method setDefaultInclude ### Parameters #### Path Parameters - **config** (Object) - Required - The default configuration object. ``` ```APIDOC ## getDefaultInclude ### Description Gets the default configuration that will be used for this plopfile if it is consumed by another plopfile using `plop.load()`. ### Method getDefaultInclude ### Returns - **Object** - The default configuration object. ``` ```APIDOC ## renderString ### Description Renders a given string using Handlebars with the provided data. ### Method renderString ### Parameters #### Path Parameters - **templateString** (String) - Required - The Handlebars template string to render. - **data** (Object) - Required - The data object to use for rendering. ### Returns - **String** - The rendered template string. ``` -------------------------------- ### Plop Initialization via package.json postinstall Script Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Automatically initialize Plop boilerplate after npm installation by adding `plop --init` to the `postinstall` script in your package.json. This ensures Plop is set up when the package is installed. ```json { "scripts": { "postinstall": "plop --init" } } ``` -------------------------------- ### Minimal Plopfile Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md A basic plopfile.js demonstrating how to define a simple generator with input prompts and an add action. ```javascript // plopfile.js export default function (plop) { plop.setGenerator('basic', { description: 'Create a file', prompts: [ { type: 'input', name: 'name', message: 'File name?' } ], actions: [ { type: 'add', path: 'files/{{name}}.txt', template: 'Hello {{name}}' } ] }); } ``` -------------------------------- ### PlopGeneratorConfig Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/04-types.md An example of how to define a generator configuration object. This includes a prompt for the component name and an action to add a new file from a template. ```typescript const config: PlopGeneratorConfig = { description: 'Create a new React component', prompts: [ { type: 'input', name: 'name', message: 'Component name?' } ], actions: [ { type: 'add', path: 'src/{{name}}.jsx', templateFile: 'template.hbs' } ] }; ``` -------------------------------- ### Get a Generator and List All Generators Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md Demonstrates how to retrieve a specific generator by its name or get a list of all available generators. ```javascript const gen = plop.getGenerator('component'); const list = plop.getGeneratorList(); ``` -------------------------------- ### Plop Bypass Prompt Example (List) Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Shows how to bypass a 'list' prompt by providing the choice name or index. ```bash # list: value name or index plop gen "choice-name" ``` -------------------------------- ### Quick Reference Source: https://github.com/plopjs/plop/blob/main/_autodocs/README.txt A fast lookup guide with common patterns, code snippets, and debugging tips for Plop. ```APIDOC ## Quick Reference ### Description This section serves as a quick reference guide for Plop users, offering fast lookups for common patterns, useful code snippets, and debugging tips. ### Content - Common patterns and usage. - Code snippets for frequent tasks. - Debugging tips and troubleshooting. ``` -------------------------------- ### Run Generator Actions with Hooks Source: https://github.com/plopjs/plop/blob/main/_autodocs/05-generator-runner.md Execute generator actions with custom lifecycle callbacks for success, failure, and comments. This example shows how to get answers from prompts and then run the actions, logging the outcome of each change or failure. ```javascript const generator = plop.getGenerator('component'); const answers = await generator.runPrompts(); const { changes, failures } = await generator.runActions(answers, { onSuccess: (change) => { console.log(`✓ ${change.type}: ${change.path}`); }, onFailure: (failure) => { console.error(`✗ ${failure.type}: ${failure.error}`); }, onComment: (msg) => { console.log(`--- ${msg} ---`); } }); if (failures.length > 0) { console.log(`${failures.length} action(s) failed`); } ``` -------------------------------- ### Complete Plopfile Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/10-plopfile-structure.md This example demonstrates setting a welcome message, registering custom helpers and partials, defining a custom action type, and creating two generators: 'component' and 'route'. The 'component' generator includes prompts for name, type, and test inclusion, with actions to add component files and modify the main index file. The 'route' generator prompts for path and HTTP method, with actions to add route files and update the routes index. ```javascript // plopfile.js import * as path from 'path'; export default function (plop) { // Set welcome message plop.setWelcomeMessage('Welcome to the Code Generator! 🚀'); // Register custom helpers plop.setHelper('pluralize', (word) => { if (word.endsWith('y')) return word.slice(0, -1) + 'ies'; return word + 's'; }); // Register partials plop.setPartial('license', '// MIT License'); // Register custom action plop.setActionType('runCommand', async (answers, config) => { const { exec } = require('child_process'); return new Promise((resolve, reject) => { exec(config.cmd, (error) => { if (error) reject(error); else resolve(`Ran: ${config.cmd}`); }); }); }); // Component generator plop.setGenerator('component', { description: 'Create a new React component', prompts: [ { type: 'input', name: 'name', message: 'Component name?', validate: (value) => { if (!value) return 'Name is required'; if (!/^[A-Z]/.test(value)) return 'Must start with capital letter'; return true; } }, { type: 'list', name: 'type', message: 'Component type?', choices: ['Functional', 'Class'] }, { type: 'confirm', name: 'addTests', message: 'Add tests?', default: true } ], actions: [ { type: 'add', path: 'src/components/{{pascalCase name}}/index.js', templateFile: 'templates/component/index.js.hbs' }, { type: 'add', path: 'src/components/{{pascalCase name}}/styles.css', templateFile: 'templates/component/styles.css.hbs' }, { type: 'add', path: 'src/components/{{pascalCase name}}/{{pascalCase name}}.test.js', templateFile: 'templates/component/test.js.hbs', skip: (data) => !data.addTests ? 'Tests skipped' : false }, { type: 'modify', path: 'src/components/index.js', pattern: /(import.*from.*;\n)/, template: "$1import {{pascalCase name}} from './{{pascalCase name}}';\n" } ] }); // Route generator plop.setGenerator('route', { description: 'Create a new API route', prompts: [ { type: 'input', name: 'path', message: 'Route path? (e.g., /api/users)' }, { type: 'list', name: 'method', message: 'HTTP method?', choices: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] } ], actions: [ { type: 'add', path: 'src/routes/{{dashCase path}}.js', templateFile: 'templates/route.js.hbs' }, { type: 'modify', path: 'src/routes/index.js', pattern: /(const routes = \[)/, template: '$1\n require("./{{dashCase path}}"),' } ] }); } ``` -------------------------------- ### Dynamic Actions Array Example Source: https://github.com/plopjs/plop/blob/main/README.md This snippet demonstrates how to use a function for the 'actions' property to conditionally add files based on user input. It requires the 'plop' library to be installed and configured. ```javascript export default function (plop) { plop.setGenerator("test", { prompts: [ { type: "confirm", name: "wantTacos", message: "Do you want tacos?", }, ], actions: function (data) { var actions = []; if (data.wantTacos) { actions.push({ type: "add", path: "folder/{{dashCase name}}.txt", templateFile: "templates/tacos.txt", }); } else { actions.push({ type: "add", path: "folder/{{dashCase name}}.txt", templateFile: "templates/burritos.txt", }); } return actions; }, }); } ``` -------------------------------- ### Install Plop Locally Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Install Plop as a development dependency for local project use. Configure an npm script in package.json to run Plop. ```bash npm install --save-dev plop ``` ```json { "scripts": { "plop": "plop" } } ``` -------------------------------- ### Plop Bypass Prompt Example (Confirm) Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Shows how to bypass a 'confirm' prompt with 'yes' or 'no'. ```bash # confirm: yes/no or y/n plop gen "yes" ``` -------------------------------- ### Initialize New Plopfile Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Bootstrap a new Plop project by running plop with the --init or --init-ts flag. This creates a basic plopfile.js and an example template directory. ```bash plop --init ``` ```bash plop --init-ts ``` -------------------------------- ### Plopfile Generator Registration Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Demonstrates how to register a generator named 'test' in a plopfile.js. ```javascript // plopfile.js export default function (plop) { plop.setGenerator('test', { prompts: [], actions: [] }); } ``` -------------------------------- ### Plop Bypass Prompt Example (Checkbox) Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Shows how to bypass a 'checkbox' prompt using comma-separated values. ```bash # checkbox: comma-separated values plop gen "opt1,opt2" ``` -------------------------------- ### Load Assets with Custom Include Config Source: https://github.com/plopjs/plop/blob/main/plop-load.md Load specific assets from a local path using a custom include configuration object. This example loads only helpers. ```javascript // loads all helpers, no generators, actionTypes or partials (even if they exist) plop.load("./plopfiles/component.js", {}, { helpers: true }); ``` -------------------------------- ### Handle File System Errors Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md This example illustrates how to handle common file system errors, such as 'EACCES' (permission denied) and 'ENOENT' (file not found), when writing to a file. ```javascript try { await fspp.writeFile('/protected/file.js', 'content'); } catch (err) { if (err.code === 'EACCES') { console.error('Permission denied'); } else if (err.code === 'ENOENT') { console.error('Parent directory does not exist'); } else { console.error('Write failed:', err.message); } } ``` -------------------------------- ### Basic Plopfile.js Configuration (ESM) Source: https://github.com/plopjs/plop/blob/main/README.md Create a plopfile.js at the root of your project to define generators. This example uses ESM syntax. ```javascript export default function (plop) { // create your generators here plop.setGenerator("basics", { description: "this is a skeleton plopfile", prompts: [], // array of inquirer prompts actions: [], // array of actions }); } ``` -------------------------------- ### CLI Reference Source: https://github.com/plopjs/plop/blob/main/_autodocs/README.txt Documentation for the Plop command-line interface, including flags, options, usage patterns, and integration examples. ```APIDOC ## CLI Reference ### Description This section provides a reference for the Plop command-line interface (CLI). It details available flags and options, common usage patterns, and examples of integration. ### Usage - Command-line flags and options. - Common usage patterns. - Integration examples. ``` -------------------------------- ### List Prompt Bypass Examples Source: https://github.com/plopjs/plop/blob/main/_autodocs/06-prompt-bypass.md Examples for bypassing 'list' prompts by specifying a choice's value, name, key, or index. Case-insensitive matching is supported for names. ```bash plop list "red" // Selects red choice ``` ```bash plop list "0" // Selects first choice by index ``` ```bash plop list "Red" // Selects by name (case-insensitive) ``` -------------------------------- ### Plop Success Message Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Displays a successful action completion. ```text ✔ add src/component.js ✔ modify src/index.js ✔ append src/routes.js ``` -------------------------------- ### CLI: Run Generator with Arguments Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md Examples of running a Plop generator from the command line with different argument patterns, including interactive mode, providing answers, skipping prompts, and using named arguments. ```bash plop component # Interactive plop component "MyComponent" # With answer to first prompt plop component "MyComponent" "tsx" # Multiple answers plop component _ "tsx" # Skip first, answer second plop component -- --name "MyComp" # Named arguments ``` -------------------------------- ### Plop Failure Message Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Displays a failed action with a reason. ```text ✖ add src/component.js File already exists ``` -------------------------------- ### Plop Scripted Generation Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Automates generator execution with bypass values and the --force flag. ```bash #!/bin/bash plop component "UserProfile" "functional" "typescript" --force plop route "dashboard" "true" "true" --force ``` -------------------------------- ### Plop CI/CD Pipeline Integration Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Example of using Plop within a GitHub Actions workflow for automated generation. ```yaml # GitHub Actions example - name: Generate boilerplate run: npm run plop -- component "MyComp" --force --dest ./generated ``` -------------------------------- ### Data Merging Priority Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/08-template-rendering.md Demonstrates how global data, action config data, and prompt answers are merged. Action data overrides global data, and prompt answers override action data. ```javascript // Global data const globalData = { version: '1.0.0' }; // Action config const actionConfig = { type: 'add', path: 'src/{{name}}.js', template: '// v{{version}}, {{name}}, data: { version: '2.0.0' } // Overrides global }; // Prompt answers const answers = { name: 'MyModule' }; // Final merged data: // { version: '2.0.0', name: 'MyModule' } // version comes from action data (not global) // name comes from answers ``` -------------------------------- ### Plop.js Generator Configuration Source: https://github.com/plopjs/plop/blob/main/_autodocs/06-prompt-bypass.md Example of a Plop.js generator configuration showing prompt names used for named arguments. ```javascript plop.setGenerator('component', { prompts: [ { type: 'input', name: 'name', message: 'Component name?' }, { type: 'list', name: 'type', message: 'Type?', choices: [...] } ], actions: [] }); ``` -------------------------------- ### Display Plop Version Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Check the installed version of Plop by executing plop with the --version or -v flag. ```bash plop --version ``` -------------------------------- ### Load from NPM Package Source: https://github.com/plopjs/plop/blob/main/plop-load.md Load assets from an NPM package (plop-pack) by specifying its name. This example loads all available helpers from the 'plop-pack-fancy-comments' package. ```javascript // loads all 3 helpers plop.load("plop-pack-fancy-comments"); ``` -------------------------------- ### Combine File Mode Constants Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md Use bitwise OR to combine file mode constants for granular permission setting. This example sets user read and execute permissions. ```javascript const mode = fspp.constants.S_IRUSR | fspp.constants.S_IXUSR; // Equivalent to 0o500 (user read + execute) await fspp.chmod('/path/to/file', mode); ``` -------------------------------- ### Plop Integration with Makefile Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Integrate Plop commands into a Makefile for build automation. This example shows how to run Plop generators using `npx` within make targets. ```makefile .PHONY: generate generate: npx plop component .PHONY: gen-typescript gen-typescript: NODE_OPTIONS='--import tsx' npx plop component --plopfile plopfile.ts ``` -------------------------------- ### Plopfile.js - Controller Generator Example Source: https://github.com/plopjs/plop/blob/main/README.md Define a 'controller' generator that prompts for a name and adds a new controller file using a Handlebars template. ```javascript export default function (plop) { // controller generator plop.setGenerator("controller", { description: "application controller logic", prompts: [ { type: "input", name: "name", message: "controller name please", }, ], actions: [ { type: "add", path: "src/{{name}}.js", templateFile: "plop-templates/controller.hbs", }, ], }); } ``` -------------------------------- ### Bypass Different Prompt Types Source: https://github.com/plopjs/plop/blob/main/_autodocs/06-prompt-bypass.md Example of bypassing various prompt types (text, confirm, list, checkbox) with their respective syntax. ```bash plop gen "text_value" "yes" "choice_name" "opt1,opt2" ``` -------------------------------- ### Append to File Content Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md This example shows how to append data to an existing file by reading its current content, performing the append operation, and then writing the modified content back. ```javascript let fileData = await fspp.readFile(fileDestPath); fileData = await doAppend(data, cfg, plop, fileData); await fspp.writeFile(fileDestPath, fileData); ``` -------------------------------- ### Plopfile with TypeScript Declarations Source: https://github.com/plopjs/plop/blob/main/README.md Example of a plopfile.js using TypeScript JSDoc declarations for code assistance. This setup helps editors provide autocompletion and type checking. ```javascript // plopfile.js export default function ( /** @type {import('plop').NodePlopAPI} */ plop, ) { // plop generator code } ``` -------------------------------- ### Plop Actions with Comments Source: https://github.com/plopjs/plop/blob/main/_autodocs/02-built-in-actions.md String entries in the actions array are printed as comments during execution. This example shows how to include comments alongside standard 'add' actions and custom async functions. ```javascript plop.setGenerator('test', { prompts: [], actions: [ '--- Creating component files ---', { type: 'add', path: 'src/index.js', template: '' }, '--- Running post-generation tasks ---', async (answers, config, plop) => { // custom action } ] }); ``` -------------------------------- ### Template File Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/08-template-rendering.md Specify template content using the `templateFile` property, referencing a file relative to the plopfile. Plop resolves the path using Node's `path.resolve()`. ```javascript // templates/component.hbs relative to plopfile { type: 'add', path: 'src/{{name}}.js', templateFile: 'templates/component.hbs' } ``` -------------------------------- ### Display Help Information Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Show all available CLI options and their descriptions by running plop with the --help or -h flag. ```bash plop --help ``` -------------------------------- ### Configure npm Script for TypeScript Plopfile (Older Node.js) Source: https://github.com/plopjs/plop/blob/main/README.md For older Node.js versions, install 'tsx' and 'cross-env', then use NODE_OPTIONS to activate the tsx loader for TypeScript plopfiles. ```json // package.json "scripts": { "plop" : "cross-env NODE_OPTIONS='--import tsx' plop --plopfile=plopfile.ts" } ``` -------------------------------- ### Load NPM Package with Renaming Include Source: https://github.com/plopjs/plop/blob/main/plop-load.md Load specific assets from an NPM package and rename them using a custom include configuration. This example loads the 'js-header' helper and renames it to 'titleComment'. ```javascript // loads only the header helper, no generators, actionTypes or partials (even if they exist) // within the plopfile and templates, the "js-header" helper is referenced as "titleComment" plop.load( "plop-pack-fancy-comments", {}, { helpers: { "js-header": "titleComment" } }, ); ``` -------------------------------- ### Initialize Plopfile Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md Use these commands to create a new Plopfile in your project. Choose between JavaScript or TypeScript. ```bash plop --init # Creates plopfile.js ``` ```bash plop --init-ts # Creates plopfile.ts ``` -------------------------------- ### dotCase Helper for Configuration Keys Source: https://github.com/plopjs/plop/blob/main/_autodocs/03-built-in-helpers.md The `dotCase` helper formats input strings into dot.case, often used for configuration keys or nested property access. The example shows its application in defining a constant key. ```handlebars export const {{constantCase name}}_KEY = '{{dotCase name}}'; // If name = "user settings" // Output: export const USER_SETTINGS_KEY = 'user.settings'; ``` -------------------------------- ### Package a Wrapper Script as a CLI Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Configure your package.json to expose your wrapper script as an executable command using the 'bin' field. ```json { "bin": { "my-gen": "./bin/cli.js" } } ``` -------------------------------- ### Checkbox Prompt Bypass Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/06-prompt-bypass.md An example of bypassing a 'checkbox' prompt with multiple selections using comma-separated values or indices. The second argument skips prompting. ```bash plop setup "" _ "ts,eslint,prettier" // First: input // Second: skip (ask user) // Third: checkbox with three selections ``` -------------------------------- ### Mixed Abort on Fail Behavior in Actions Source: https://github.com/plopjs/plop/blob/main/_autodocs/05-generator-runner.md This example shows a mix of `abortOnFail` settings within a generator's actions. The first action will stop execution on failure, while the second allows subsequent actions to proceed. ```javascript actions: [ { type: 'add', path: 'src/file1.js', template: '', abortOnFail: true // Any failure here stops everything }, { type: 'add', path: 'src/file2.js', template: '', abortOnFail: false // Failure here allows action 3 to run }, { type: 'add', path: 'src/file3.js', template: '' } ] ``` -------------------------------- ### Transform Function Example: Code Formatting Source: https://github.com/plopjs/plop/blob/main/_autodocs/08-template-rendering.md Use a transform function to format rendered code, for example, using Prettier. This is available for 'add', 'addMany', 'modify', and 'append' actions. ```javascript { type: 'add', path: 'src/{{name}}.js', template: 'const x=1;const y=2;', transform: async (template, data) => { // Use prettier to format code const prettier = await import('prettier'); return prettier.format(template, { parser: 'babel' }); } } ``` -------------------------------- ### Action Data Merging Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/05-generator-runner.md Demonstrates how Plop merges prompt answers, action data, and global data. Action data is merged after prompt answers, and if action data is a function, its result is awaited before merging. ```javascript const answers = { name: 'UserCard' }; const action = { type: 'add', path: 'src/{{name}}.js', template: '// Author: {{author}}', data: { author: 'John' } }; // Merged data becomes: { name: 'UserCard', author: 'John' } // Template renders with both variables ``` -------------------------------- ### Transform Function Example: Conditional Processing Source: https://github.com/plopjs/plop/blob/main/_autodocs/08-template-rendering.md Conditionally modify the template based on provided data. This example removes whitespace if the 'minify' data property is true, useful for 'modify' actions. ```javascript { type: 'modify', path: 'src/index.js', pattern: /(module.exports)/, template: '$1', transform: (template, data) => { if (data.minify) { return template.replace(/\s+/g, ''); } return template; } } ``` -------------------------------- ### Create a Plop Wrapper CLI - index.js Source: https://github.com/plopjs/plop/blob/main/README.md This JavaScript file serves as the entry point for a custom CLI project that wraps Plop. It uses `minimist` to parse command-line arguments and `plop` to prepare and execute Plop configurations. ```javascript #!/usr/bin/env node import path from "node:path"; import minimist from "minimist"; import { Plop, run } from "plop"; const args = process.argv.slice(2); const argv = minimist(args); import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); Plop.prepare( { cwd: argv.cwd, configPath: path.join(__dirname, "plopfile.js"), preload: argv.preload || [], completion: argv.completion, }, (env) => Plop.execute(env, run), ); ``` -------------------------------- ### Add Action: Create Component Files Source: https://github.com/plopjs/plop/blob/main/_autodocs/02-built-in-actions.md Use the 'add' action to create multiple files for a new component, specifying template files for content and optionally using skipIfExists. ```javascript plop.setGenerator('component', { prompts: [{ type: 'input', name: 'name', message: 'Component name?' }], actions: [ { type: 'add', path: 'src/components/{{dashCase name}}/index.js', templateFile: 'templates/component.js.hbs' }, { type: 'add', path: 'src/components/{{dashCase name}}/styles.css', template: '/* Styles for {{name}} */', skipIfExists: true } ] }); ``` -------------------------------- ### List Plop Generators Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md Execute this JavaScript code to get a list of all generators defined in your plopfile.js. ```javascript const plop = await nodePlop('./plopfile.js'); console.log(plop.getGeneratorList()); ``` -------------------------------- ### Configuration and Path Methods Source: https://github.com/plopjs/plop/blob/main/packages/plop/README.md Methods for setting and retrieving Plop's configuration and file paths. ```APIDOC ## setWelcomeMessage ### Description Customizes the welcome message displayed when the `plop` command is run, prompting the user to choose a generator. ### Method setWelcomeMessage ### Parameters #### Path Parameters - **message** (String) - Required - The custom welcome message. ``` ```APIDOC ## setPlopfilePath ### Description Sets the internal `plopfilePath` value, which is used by Plop to locate resources such as template files. ### Method setPlopfilePath ### Parameters #### Path Parameters - **path** (String) - Required - The absolute path to the plopfile. ``` ```APIDOC ## getPlopfilePath ### Description Returns the absolute path to the currently used plopfile. ### Method getPlopfilePath ### Returns - **String** - The absolute path to the plopfile. ``` ```APIDOC ## getDestBasePath ### Description Returns the base path that Plop uses when creating new files. ### Method getDestBasePath ### Returns - **String** - The base destination path. ``` ```APIDOC ## setDefaultInclude ### Description Sets the default configuration to be used when this plopfile is consumed by another plopfile using `plop.load()`. ### Method setDefaultInclude ### Parameters #### Path Parameters - **config** (Object) - Required - The default configuration object. ``` ```APIDOC ## getDefaultInclude ### Description Gets the default configuration that will be used for this plopfile if it is consumed by another plopfile using `plop.load()`. ### Method getDefaultInclude ### Returns - **Object** - The default configuration object. ``` -------------------------------- ### Main Entry Point Source: https://github.com/plopjs/plop/blob/main/_autodocs/00-INDEX.md The main entry point for using Plop.js programmatically. It initializes Plop and returns an API object for further interaction. An optional Plopfile path and configuration can be provided. ```APIDOC ## Main Entry Point ### Description Initializes Plop and returns an API object for programmatic interaction. An optional Plopfile path and configuration can be provided. ### Method Signature `nodePlop(plopfilePath?: string, plopCfg?: PlopCfg): Promise` ### Parameters - **plopfilePath** (string) - Optional - The path to the Plopfile. - **plopCfg** (PlopCfg) - Optional - Configuration object for Plop. ``` -------------------------------- ### makeDir(path) Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md Creates a directory, including any necessary parent directories. The function takes the directory path as a string argument and returns a Promise that resolves when the directory is created. It does not error if the directory already exists and recursively creates parent directories if they are missing. ```APIDOC ## makeDir(path) ### Description Creates a directory, including any necessary parent directories. The function takes the directory path as a string argument and returns a Promise that resolves when the directory is created. It does not error if the directory already exists and recursively creates parent directories if they are missing. ### Parameters #### Path Parameters - **path** (string) - Required - Directory path to create ### Returns Promise that resolves when directory is created. ### Behavior Recursively creates parent directories if they don't exist. Does not error if directory already exists. ### Example ```javascript await fspp.makeDir('/path/to/nested/directory'); // Creates: /path/to/nested/directory (and any missing parents) ``` ``` -------------------------------- ### Create Directory Recursively Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md Creates a directory at the specified path, including any necessary parent directories. The operation does not error if the directory already exists. ```javascript await fspp.makeDir('/path/to/nested/directory'); // Creates: /path/to/nested/directory (and any missing parents) ``` -------------------------------- ### Plop Component Generator with Prompts Source: https://github.com/plopjs/plop/blob/main/_autodocs/09-cli-reference.md Initiates the 'component' generator, prompting the user for input. ```bash plop component # Interactive prompts for name, type, etc. ``` -------------------------------- ### Get List of Registered Handlebars Partials Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Use `getPartialList` to obtain an array of names for all Handlebars partials that have been registered with Plop. ```javascript plop.getPartialList(): string[] ``` -------------------------------- ### Create a Plop Wrapper CLI - package.json Source: https://github.com/plopjs/plop/blob/main/README.md This JSON configuration file defines a Node.js project that acts as a CLI wrapper for Plop. It includes dependencies, scripts for running Plop, and specifies a binary for global execution. ```json { "name": "create-your-name-app", "version": "1.0.0", "main": "index.js", "scripts": { "start": "plop" }, "bin": { "create-your-name-app": "./index.js" }, "preferGlobal": true, "dependencies": { "plop": "^3.0.0" } } ``` -------------------------------- ### Plopfile Action Configuration Source: https://github.com/plopjs/plop/blob/main/_autodocs/10-plopfile-structure.md Defines a basic 'add' action to create a component file, referencing a template. Use this to specify file paths and template locations. ```javascript { type: 'add', path: 'src/components/{{name}}/index.js', templateFile: 'plop-templates/component/index.js.hbs' } ``` -------------------------------- ### stat(path) Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md Get file/directory metadata. This function retrieves information about a file or directory, such as its type, size, and modification times. ```APIDOC ## stat(path) ### Description Get file/directory metadata. This function retrieves information about a file or directory, such as its type, size, and modification times. ### Signature ```javascript function stat(path: string): Promise ``` ### Parameters #### Path Parameters - **path** (string) - Required - File or directory path ### Returns Promise resolving to fs.Stats object. **Stats Properties:** - `isFile()`: Boolean, true if regular file - `isDirectory()`: Boolean, true if directory - `isSymbolicLink()`: Boolean, true if symbolic link - `mode`: File mode/permissions (number) - `size`: File size in bytes - `mtime`: Modification time (Date) - `atime`: Access time (Date) - `ctime`: Change time (Date) - `birthtime`: Creation time (Date) ### Throws If path doesn't exist. ### Example ```javascript const stats = await fspp.stat('/path/to/file.js'); console.log(stats.isFile()); // true console.log(stats.size); // File size in bytes console.log(stats.mode); // File permissions ``` ``` -------------------------------- ### Get List of Custom Helpers Source: https://github.com/plopjs/plop/blob/main/_autodocs/03-built-in-helpers.md Retrieve a list of all custom helpers that have been registered with Plop. This method does not include built-in helpers. ```javascript const customHelpers = plop.getHelperList(); // Returns only helpers added via setHelper(), not built-in ones ``` -------------------------------- ### Load All Assets from a Path Source: https://github.com/plopjs/plop/blob/main/plop-load.md Load all available assets (generators, helpers, actionTypes, partials) from a specified local path by passing `true` as the include argument. ```javascript // loads all 5 generators, all helpers, actionTypes and partials (if they exist) plop.load("./plopfiles/component.js", {}, true); ``` -------------------------------- ### Load Multiple Sources (NPM and Path) Source: https://github.com/plopjs/plop/blob/main/plop-load.md Load assets from multiple sources simultaneously, including both NPM packages and local file paths. Each source uses its default include configuration. ```javascript // uses the default include config for each item plop.load(["plop-pack-fancy-comments", "./plopfiles/component.js"]); ``` -------------------------------- ### Example of Bypassing Prompts Source: https://github.com/plopjs/plop/blob/main/_autodocs/05-generator-runner.md Demonstrates bypassing prompts in a generator with three prompt types: input, skip, and list selection. ```javascript // Generator with 3 prompts await generator.runPrompts([ 'ComponentName', // First prompt: input '_', // Second prompt: skip, ask user 'typescript' // Third prompt: list selection ]); ``` -------------------------------- ### Get List of All Registered Custom Action Types Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Retrieves an array containing the names of all custom action types that have been registered with Plop. ```javascript const actionTypes = plop.getActionTypeList(); // actionTypes will be an array of strings, e.g., ['runShellCommand'] ``` -------------------------------- ### Registering a Handlebars Partial Source: https://github.com/plopjs/plop/blob/main/README.md Use setPartial to register custom Handlebars partials. This example registers a partial for a title with a name placeholder. ```javascript export default function (plop) { plop.setPartial("myTitlePartial", "

{{titleCase name}}

"); // used in template as {{> myTitlePartial }} } ``` -------------------------------- ### Initialize TypeScript Plopfile Source: https://github.com/plopjs/plop/blob/main/README.md Create a new TypeScript plopfile using the --init-ts flag or manually. This is the first step for using TypeScript with Plop. ```ts // plopfile.ts import type { NodePlopAPI } from "plop"; export default function (plop: NodePlopAPI) { // plop generator code } ``` -------------------------------- ### Inline Template Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/08-template-rendering.md Use the `template` property to define inline templates for actions. This is suitable for simple, static template content. ```javascript { type: 'add', path: 'src/{{name}}.js', template: '// {{name}} component' } ``` -------------------------------- ### Add Multiple Files Action Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md Use 'addMany' to create multiple files from a base directory and a glob pattern. Files will be placed in the specified destination. ```javascript { type: 'addMany', destination: 'src/{{name}}', base: 'templates/component/', templateFiles: 'templates/component/**/*.hbs' } ``` -------------------------------- ### Get Default Include Configuration Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Retrieve the current default include configuration using `getDefaultInclude`. This configuration determines which assets are loaded by default. ```javascript function getDefaultInclude(): object ``` -------------------------------- ### Get Plopfile Path Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Retrieves the absolute path to the plopfile directory. This is useful for resolving template paths relative to the plopfile's location. ```javascript const plopDir = plop.getPlopfilePath(); // resolves template paths relative to this directory ``` -------------------------------- ### Add File Action Source: https://github.com/plopjs/plop/blob/main/_autodocs/11-quick-reference.md Use the 'add' action to create a new file from a template. Specify the destination path and the template file to use. ```javascript { type: 'add', path: 'src/{{dashCase name}}/index.js', templateFile: 'templates/component.hbs' } ``` -------------------------------- ### Get List of Registered Generators Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Retrieve a list of all generators that have been registered with Plop. Each item in the list includes the generator's name and description. ```javascript const generators = plop.getGeneratorList(); generators.forEach(gen => { console.log(`${gen.name}: ${gen.description}`); }); ``` -------------------------------- ### Load Specific Helper from Path Source: https://github.com/plopjs/plop/blob/main/plop-load.md Load only a specific helper asset from a local path by providing an array of helper names in the include configuration. ```javascript // loads only the "js-header" helper, no generators, actionTypes or partials (even if they exist) plop.load("./plopfiles/component.js", {}, { helpers: ["js-header"] }); ``` -------------------------------- ### Registering a Handlebars Helper Source: https://github.com/plopjs/plop/blob/main/README.md Use setHelper to register custom Handlebars helpers. This example shows how to register a helper for converting text to uppercase. ```javascript export default function (plop) { plop.setHelper("upperCase", function (text) { return text.toUpperCase(); }); // or in es6/es2015 plop.setHelper("upperCase", (txt) => txt.toUpperCase()); } ``` -------------------------------- ### File System Utilities Source: https://github.com/plopjs/plop/blob/main/_autodocs/README.txt Reference for promise-based file operations, including reading/writing files, directory operations, and permissions handling. ```APIDOC ## File System Utilities ### Description This section provides documentation for the promise-based file system utilities used within Plop. This includes operations for reading and writing files, managing directories, and handling file permissions. ### Utilities - Promise-based file read/write operations. - Directory creation, deletion, and listing. - File and directory permission handling. ``` -------------------------------- ### nodePlop(plopfilePath?, plopCfg?) Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Initializes the Node-Plop API. It loads a plopfile and returns an API object for interacting with Plop's features. It can optionally take a plopfile path and configuration object. ```APIDOC ## nodePlop(plopfilePath?, plopCfg?) ### Description Initializes the node-plop API for a given plopfile. ### Signature ```javascript async function nodePlop(plopfilePath: string, plopCfg?: PlopCfg): Promise ``` ### Parameters #### Path Parameters - **plopfilePath** (string) - Optional - Absolute path to the plopfile to load. If empty, loads from current working directory. - **plopCfg** (PlopCfg) - Optional - Configuration object with destBasePath and force options. ### Returns Promise resolving to `NodePlopAPI` object with all plop methods. ### Throws If the plopfile cannot be imported or executed. ### Example ```javascript import nodePlop from 'node-plop'; const plop = await nodePlop('/path/to/plopfile.js'); const generators = plop.getGeneratorList(); const generator = plop.getGenerator('component'); const answers = await generator.runPrompts(); const result = await generator.runActions(answers); ``` ``` -------------------------------- ### Transform Function Example Source: https://github.com/plopjs/plop/blob/main/_autodocs/05-generator-runner.md This snippet demonstrates how to use a transform function to modify rendered template content. It trims whitespace from each line of the template. ```javascript { type: 'add', path: 'src/{{name}}.js', template: 'const x = 1;\nconst y = 2;', transform: (template) => { // Format/prettier output const lines = template.split('\n'); return lines.map(line => line.trim()).join('\n'); } } ``` -------------------------------- ### Add Binary and Text Files Source: https://github.com/plopjs/plop/blob/main/_autodocs/07-file-system-utilities.md Demonstrates how to configure Plop actions to add both binary files (copied directly) and text files (processed as templates). Binary files are detected using the 'isbinaryfile' library and copied using raw read/write operations. ```javascript // This template will be detected as binary (PNG) // and copied without template processing { type: 'add', path: 'public/logo.png', templateFile: 'templates/logo.png' } // This template is text and will be processed { type: 'add', path: 'src/component.js', templateFile: 'templates/component.js.hbs' } ``` -------------------------------- ### setDefaultInclude(config) Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Sets the default configuration for what gets loaded when this plopfile is consumed by another. This is useful for controlling the default import behavior for nested Plop configurations. ```APIDOC ## setDefaultInclude(config) ### Description Set default configuration for what gets loaded when this plopfile is consumed by another. ### Signature ```javascript function setDefaultInclude(config: IncludeDefinitionConfig): void ``` ### Parameters #### Path Parameters - **config** (IncludeDefinitionConfig) - Yes - Config with generators, helpers, partials, actionTypes boolean flags ``` -------------------------------- ### Transform Function Example: JSON Indentation Source: https://github.com/plopjs/plop/blob/main/_autodocs/08-template-rendering.md Pretty-print JSON output using a transform function by parsing and stringifying the template. This can be applied to actions like 'add'. ```javascript { type: 'add', path: 'config.json', template: '{"name":"{{name}}","debug":true}', transform: (template) => { // Pretty-print JSON const obj = JSON.parse(template); return JSON.stringify(obj, null, 2); } } ``` -------------------------------- ### Initialize Node-Plop API Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Use this function to initialize the Node-Plop API for a given plopfile. It returns a Promise that resolves to the NodePlopAPI object. ```javascript import nodePlop from 'node-plop'; const plop = await nodePlop('/path/to/plopfile.js'); const generators = plop.getGeneratorList(); const generator = plop.getGenerator('component'); const answers = await generator.runPrompts(); const result = await generator.runActions(answers); ``` -------------------------------- ### Access package.json Properties with pkg Helper Source: https://github.com/plopjs/plop/blob/main/_autodocs/03-built-in-helpers.md Use the `pkg` helper to retrieve values from your project's package.json file. It supports dot-notation and bracket notation for nested properties. Returns an empty string if the property is not found or package.json is missing. ```handlebars // package.json: // { // "name": "my-app", // "version": "1.0.0", // "author": { "name": "John", "email": "john@example.com" } // } /** * Package: {{pkg "name"}} * Version: {{pkg "version"}} * Author: {{pkg "author.name"}} ({{pkg "author.email"}}) */ // Outputs: // /** // * Package: my-app // * Version: 1.0.0 // * Author: John (john@example.com) // */ ``` ```handlebars // Bracket notation is converted to dot notation internally {{pkg "dependencies[react]"}} // Same as {{pkg "dependencies.react"}} ``` -------------------------------- ### Get List of Registered Handlebars Helpers Source: https://github.com/plopjs/plop/blob/main/_autodocs/01-api-reference-node-plop.md Use `getHelperList` to retrieve an array containing the names of all custom Handlebars helpers that have been registered. Built-in helpers are excluded from this list. ```javascript plop.getHelperList(): string[] ``` -------------------------------- ### Using package.json Data in Templates Source: https://github.com/plopjs/plop/blob/main/_autodocs/10-plopfile-structure.md Injects data from the project's package.json into generated files. The `pkg` helper loads package.json from the destination directory. ```javascript { type: 'add', path: 'src/{{name}}.js', template: '// {{pkg "name"}} v{{pkg "version"}}' } ``` -------------------------------- ### Generate Changelog for Release Source: https://github.com/plopjs/plop/blob/main/CONTRIBUTING.md Execute this command when a maintainer is ready to publish. It generates the CHANGELOG file based on the added changesets. ```bash yarn changeset version ```