Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Consistency Made Simple

License

NotificationsYou must be signed in to change notification settings

plopjs/plop

Repository files navigation

Micro-generator framework that makes it easy for an entire team to create files with a level of uniformity.plop demo

Documentation also available on plopjs.com

Getting Started

npm npm

What is Plop?

Plop is what I like to call a "micro-generator framework." Now, I call it that because it is a small tool that gives you a simple way to generate code or any other type of flat text files in a consistent way. You see, we all create structures and patterns in our code (routes, controllers, components, helpers, etc). These patterns change and improve over time so when you need to create a NEWinsert-name-of-pattern-here, it's not always easy to locate the files in your codebase that represent the current "best practice." That's where plop saves you. With plop, you have your "best practice" method of creating any given pattern in CODE. Code that can easily be run from the terminal by typingplop. Not only does this save you from hunting around in your codebase for the right files to copy, but it also turns "the right way" into "the easiest way" to make new files.

If you boil plop down to its core, it is basically glue code betweeninquirer prompts andhandlebar templates.

This documentation is a work in progress. If you have great ideas, I'd love to hear them.

Installation

1. Add plop to your project

$ npm install --save-dev plop

2. Install plop globally (optional, but recommended for easy access)

$ npm install -g plop

3. Create a plopfile.js at the root of your project

exportdefaultfunction(plop){// create your generators hereplop.setGenerator('basics',{description:'this is a skeleton plopfile',prompts:[],// array of inquirer promptsactions:[]// array of actions});};

export default is only allowed in NodeJS inside "ESM" supported files.To use this syntax, yourplopfile must be either:

  • An ESM .js file with type: "module" in package.json
  • An ESM .mjs file with any type declared in package.json

Alternatively, you can have aplopfile withmodule.exports = function (plop) instead.Forthis syntax, yourplopfile must be either:

  • A CommonJS .js file with type: "commonjs" in package.json
  • A CommonJS .cjs file with any type declared in package.json

Your First Plopfile

A plopfile starts its life as a node module that exports a function which accepts theplop object as its first parameter.

exportdefaultfunction(plop){};

Theplop object exposes the plop API object which contains thesetGenerator(name, config) function. This is the function that you use to (wait for it) create a generator for this plopfile. Whenplop is run from the terminal in this directory (or any sub-directory), a list of these generators will be displayed.

Let's try setting up a basic generator to see how that looks.

exportdefaultfunction(plop){// controller generatorplop.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'}]});};

Thecontroller generator we created above will ask us 1 question, and create 1 file. This can be expanded to ask as many questions as needed, and create as many files as needed. There are also additional actions that can be used to alter our codebase in different ways.

Using Prompts

Plop uses theinquirer.js library to gather user data. A list ofprompt types can be found on the inquirer official website.

CLI Usage

Once plop is installed, and you have created a generator, you are ready to run plop from the terminal. Runningplop with no parameters will present you with a list of generators to pick from. You can also runplop [generatorName] to trigger a generator directly. If you did not install plop globally, you will need to setup an npm script to run plop for you.

// package.json{    ...,"scripts":{"plop":"plop"},    ...}

Bypassing Prompts

Once you get to know a project (and its generators) well, you may want to provide answers to the prompts when you run the generator. If I have (for instance) acomponent generator that has one prompt (name), I can run that generator usingplop component "some component name" and it will immediately execute as though I had typed "some component name" into the prompt. If that same generator had a second prompt, the same input would have resulted in the user being prompted for the second value.

Prompts likeconfirm andlist try to make sense of your input as best they can. For instance entering "y", "yes", "t", or "true" for a confirm prompt will result in a booleantrue value. You can select items from a list using their value, index, key, or name. Checkbox prompts can accept a comma separated list of values in order to select multiples.

plop bypass demo

If you want to provide bypass input for the second prompt but not the first, you can use an underscore "_" to skip the bypass (ieplop component _ "input for second prompt").

Plop comes with bypass logic built-in for standard inquirer prompts, but there are also ways to provide custom logic for how to handle user input for a specific prompt.

If you have published a 3rd party inquirer prompt plugin and would like to support bypass functionality for plop users out of the box, that is covered inanother section of this documentation.

Bypassing Prompts (by Name)

You can also bypass prompts by name using-- and then providing arguments for each prompt that you'd like to bypass. Examplesbelow.

Bypass Examples

## Bypassing both prompt 1 and 2$ plop component "my component" react$ plop component -- --name "my component" --type react## Bypassing only prompt 2 (will be prompted for name)$ plop component _ react$ plop component -- --type react

Running a Generator Forcefully

By default Plop actions keep your files safe by failing when things look fishy. The most obvious example of this is not allowing anadd action to overwrite a file that already exists. Plop actions individually support theforce property but you can also use the--force flag when running Plop from the terminal. Using the--force flag will tell every action to run forcefully. With great power...🕷

Using TypeScript plopfiles

Plop bundles TypeScript declarations and supports TypeScript plopfiles viatsx loaders, a feature ofNodeJS command line imports.

First, make a TypesScript plopfile usingplop --init-ts or by hand:

// plopfile.tsimport{NodePlopAPI}from'plop';exportdefaultfunction(plop:NodePlopAPI){// plop generator code};

Next, installtsx and optionallycross-env:

npm i -D tsx cross-env

Finally, useNODE_OPTIONS to activate the tsx loader. Now Plop can import yourplopfile.ts:

Node.js v20.6 and above

// package.json"scripts": {"cross-env NODE_OPTIONS='--import tsx' plop --plopfile=plopfile.ts"}

Node.js v20.5.1 and below

// package.json"scripts": {"cross-env NODE_OPTIONS='--loader tsx' plop --plopfile=plopfile.ts"}

Why Generators?

Because when you create your boilerplate separate from your code, you naturally put more time and thought into it.

Because saving your team (or yourself) 5-15 minutes when creating every route, component, controller, helper, test, view, etc...really adds up.

Becausecontext switching is expensive and saving time is not the onlybenefit to automating workflows

Plopfile API

The plopfile api is the collection of methods that are exposed by theplop object. Most of the work is done bysetGenerator but this section documents the other methods that you may also find useful in your plopfile.

TypeScript Support

Plop bundles TypeScript declarations. Seeusing TypeScript plopfiles for more details.

JSDoc Support

Whether or not you write your plopfile in TypeScript, many editors will offer code assistance via JSDoc declarations.

// plopfile.jsexportdefaultfunction(/**@type {import('plop').NodePlopAPI} */plop){// plop generator code};

Main Methods

These are the methods you will commonly use when creating a plopfile. Other methods that are mostly for internal use are list in theother methods section.

MethodParametersReturnsDescription
setGeneratorString,GeneratorConfigPlopGeneratorsetup a generator
setHelperString, Functionsetup handlebars helper
setPartialString, Stringsetup a handlebars partial
setActionTypeString,CustomActionregister a custom action type
setPromptString, InquirerPromptregisters a custom prompt type with inquirer
loadArray[String], Object, Objectloads generators, helpers and/or partials from another plopfile or npm module

setHelper

setHelper directly corresponds to the handlebars methodregisterHelper. So if you are familiar withhandlebars helpers, then you already know how this works.

exportdefaultfunction(plop){plop.setHelper('upperCase',function(text){returntext.toUpperCase();});// or in es6/es2015plop.setHelper('upperCase',(txt)=>txt.toUpperCase());};

setPartial

setPartial directly corresponds to the handlebars methodregisterPartial. So if you are familiar withhandlebars partials, then you already know how this works.

exportdefaultfunction(plop){plop.setPartial('myTitlePartial','<h1>{{titleCase name}}</h1>');// used in template as {{> myTitlePartial }}};

setActionType

setActionType allows you to create your own actions (similar toadd ormodify) that can be used in your plopfiles. These are basically highly reusablecustom action functions.

FunctionSignature Custom Action

ParametersTypeDescription
answersObjectAnswers to the generator prompts
configActionConfigThe object in the "actions" array for the generator
plopPlopfileApiThe plop api for the plopfile where this action is being run
exportdefaultfunction(plop){plop.setActionType('doTheThing',function(answers,config,plop){// do somethingdoSomething(config.configProp);// if something went wrongthrow'error message';// otherwisereturn'success status message';});// or do async things inside of an actionplop.setActionType('doTheAsyncThing',function(answers,config,plop){// do somethingreturnnewPromise((resolve,reject)=>{if(success){resolve('success status message');}else{reject('error message');}});});// use the custom actionplop.setGenerator('test',{prompts:[],actions:[{type:'doTheThing',configProp:'available from the config param'},{type:'doTheAsyncThing',speed:'slow'}]});};

setPrompt

Inquirer provides many types of prompts out of the box, but it also allows developers to build prompt plugins. If you'd like to use a prompt plugin, you can register it withsetPrompt. For more details see theInquirer documentation for registering prompts. Also check out theplop community driven list of custom prompts.

importautocompletePromptfrom'inquirer-autocomplete-prompt';exportdefaultfunction(plop){plop.setPrompt('autocomplete',autocompletePrompt);plop.setGenerator('test',{prompts:[{type:'autocomplete',...}]});};

setGenerator

The config object needs to includeprompts andactions (description is optional). The prompts array is passed toinquirer. Theactions array is a list of actions to take (described in greater detail below)

InterfaceGeneratorConfig

PropertyTypeDefaultDescription
description[String]short description of what this generator does
promptsArray[InquirerQuestion]questions to ask the user
actionsArray[ActionConfig]actions to perform

If your list of actions needs to be dynamic, take a look atusing a dynamic actions array.

InterfacePlopGenerator

PropertyTypeDefaultDescription
runPromptsFunctiona function to run the prompts within a generator
runActionsFunctiona function to run the actions within a generator

This interface also contains all properties fromGeneratorConfig

InterfaceActionConfig

The following properties are the standard properties that plop handles internally. Other properties will be required depending on thetype of action. Also take a look at thebuilt-in actions.

PropertyTypeDefaultDescription
typeStringthe type of action (add,modify,addMany,etc)
forceBooleanfalseperforms the actionforcefully (means different things depending on the action)
dataObject / Function{}specifies data that should be mixed with user prompt answers when running this action
abortOnFailBooleantrueif this action fails for any reason abort all future actions
skipFunctionan optional function that specifies if the action should run

Thedata property on anyActionConfig can also be aFunction that returns anObject or aFunction that returns aPromise that resolves with anObject.

Theskip function on anyActionConfig is optional and should return a string if the action should be skipped. The return value is the reason to skip the action.

Instead of an Action Object, afunction can also be used

Other Methods

MethodParametersReturnsDescription
getHelperStringFunctionget the helper function
getHelperListArray[String]get a list of helper names
getPartialStringStringget a handlebars partial by name
getPartialListArray[String]get a list of partial names
getActionTypeStringCustomActionget an actionType by name
getActionTypeListArray[String]get a list of actionType names
setWelcomeMessageStringCustomizes the displayed message that asks you to choose a generator when you runplop.
getGeneratorStringGeneratorConfigget thePlopGenerator by name
getGeneratorListArray[Object]gets an array of generator names and descriptions
setPlopfilePathStringset theplopfilePath value which is used internally to locate resources like template files
getPlopfilePathStringreturns the absolute path to the plopfile in use
getDestBasePathStringreturns the base path that is used when creating files
setDefaultIncludeObjectObjectsets the default config that will be used for this plopfile if it is consumed by another plopfile usingplop.load()
getDefaultIncludeStringObjectgets the default config that will be used for this plopfile if it is consumed by another plopfile usingplop.load()
renderStringString, ObjectStringRuns the first parameter (String) through the handlebars template renderer using the second parameter (Object) as the data. Returns the rendered template.

Built-In Actions

There are several types of built-in actions you can use in yourGeneratorConfig. You specify whichtype of action (all paths are based on the location of the plopfile), and a template to use.

TheAdd,AddMany andModify actions have an optionaltransform method that can be used to transform the template result before it is written to disk. Thetransform function receives the template result or file contents as astring and the action data as arguments. It must return astring or aPromise that resolves to astring.

Add

Theadd action is used to (you guessed it) add a file to your project. The path property is a handlebars template that will be used to create the file by name. The file contents will be determined by thetemplate ortemplateFile property.

PropertyTypeDefaultDescription
pathStringa handlebars template that (when rendered) is the path of the new file
templateStringa handlebars template that should be used to build the new file
templateFileStringa path a file containing thetemplate
skipIfExistsBooleanfalseskips a file if it already exists (instead of failing)
transformFunctionan optional function that can be used to transform the template result before writing the file to disk
skipFunctioninherited fromActionConfig
forceBooleanfalseinherited fromActionConfig (overwrites files if they exist)
dataObject{}inherited fromActionConfig
abortOnFailBooleantrueinherited fromActionConfig

AddMany

TheaddMany action can be used to add multiple files to your project with a single action. Thedestination property is a handlebars template that will be used to identify the folder that the generated files should go into. Thebase property can be used to alter what section of the template paths should be omitted when creating files. The paths located by thetemplateFiles glob can use handlebars syntax in their file/folder names if you'd like the added file names to be unique (example:{{ dashCase name }}.spec.js).

PropertyTypeDefaultDescription
destinationStringa handlebars template that (when rendered) is the destination folder for the new files
baseStringthe section of the path that should be excluded when adding files to thedestination folder
templateFilesGlobglob pattern that matches multiple template files to be added
stripExtensions[String]['hbs']file extensions that should be stripped fromtemplateFiles files names while being added to thedestination
globOptionsObjectglob options that change how to match to the template files to be added
verboseBooleantrueprint each successfully added file path
transformFunctionan optional function that can be used to transform the template result before writing each file to disk
skipFunctioninherited fromActionConfig
skipIfExistsBooleanfalseinherited fromAdd (skips a file if it already exists)
forceBooleanfalseinherited fromActionConfig (overwrites files if they exist)
dataObject{}inherited fromActionConfig
abortOnFailBooleantrueinherited fromActionConfig

Modify

Themodify action can be used two ways. You can use apattern property to find/replace text in the file located at thepath specified, or you can use atransform function to transform the file contents. Bothpattern andtransform can be used at the same time (transform will happen last). More details on modify can be found in the example folder.

PropertyTypeDefaultDescription
pathStringhandlebars template that (when rendered) is the path of the file to be modified
patternRegExpend‑of‑fileregular expression used to match text that should be replaced
templateStringhandlebars template that should replace what was matched by thepattern. capture groups are available as $1, $2, etc
templateFileStringpath a file containing thetemplate
transformFunctionan optional function that can be used to transform the file before writing it to disk
skipFunctioninherited fromActionConfig
dataObject{}inherited fromActionConfig
abortOnFailBooleantrueinherited fromActionConfig

Append

Theappend action is a commonly used subset ofmodify. It is used to append data in a file at a particular location.

PropertyTypeDefaultDescription
pathStringhandlebars template that (when rendered) is the path of the file to be modified
patternRegExp, Stringregular expression used to match text where the append should happen
uniqueBooleantruewhether identical entries should be removed
separatorStringnew linethe value that separates entries
templateStringhandlebars template to be used for the entry
templateFileStringpath a file containing thetemplate
dataObject{}inherited fromActionConfig
abortOnFailBooleantrueinherited fromActionConfig

Custom (Action Function)

TheAdd andModify actions will take care of almost every case that plop is designed to handle. However, plop does offer custom action functions for the node/js guru. A custom action function is a function that is provided in the actions array.

  • Custom action functions are executed by plop with the sameCustomAction function signature.
  • Plop will wait for the custom action to complete before executing the next action.
  • The function must let plop known what’s happening through the return value. If you return aPromise, we won’t start other actions until the promise resolves. If you return a message (String), we know that the action is done and we’ll report the message in the status of the action.
  • A custom action fails if the promise is rejected, or the function throws anException

See theexample plopfile for a sample synchronous custom action.

Comments

Comment lines can be added to the actions array by adding a string in place of an action config object. Comments are printed to the screen when plop comes to them and have no functionality of their own.

Built-In Helpers

There are a few helpers that I have found useful enough to include with plop. They are mostly case modifiers, but here is the complete list.

Case Modifiers

  • camelCase: changeFormatToThis
  • snakeCase: change_format_to_this
  • dashCase/kebabCase: change-format-to-this
  • dotCase: change.format.to.this
  • pathCase: change/format/to/this
  • properCase/pascalCase: ChangeFormatToThis
  • lowerCase: change format to this
  • sentenceCase: Change format to this,
  • constantCase: CHANGE_FORMAT_TO_THIS
  • titleCase: Change Format To This

Other Helpers

  • pkg: look up a property from a package.json file in the same folder as the plopfile.

Taking it Further

There is not a lot needed to get up and running on some basic generators. However, if you want to take your plop-fu further, read on young padawan.

Using a Dynamic Actions Array

Alternatively, theactions property of theGeneratorConfig can itself be a function that takes the answers data as a parameter and returns the actions array.

This allows you to adapt the actions array based on provided answers:

exportdefaultfunction(plop){plop.setGenerator('test',{prompts:[{type:'confirm',name:'wantTacos',message:'Do you want tacos?'}],actions:function(data){varactions=[];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'});}returnactions;}});};

3rd Party Prompt Bypass

If you have written an inquirer prompt plugin and want to support plop's bypass functionality, the process is pretty simple. The plugin object that your prompt exports should have abypass function. Thisbypass function will be run by plop with the user's input as the first parameter and the prompt config object as the second parameter. The value that this function returns will be added to the answer data object for that prompt.

// My confirmation inquirer pluginexportdefaultMyConfirmPluginConstructor;functionMyConfirmPluginConstructor(){// ...your main plugin codethis.bypass=(rawValue,promptConfig)=>{constlowerVal=rawValue.toString().toLowerCase();consttrueValues=['t','true','y','yes'];constfalseValues=['f','false','n','no'];if(trueValues.includes(lowerVal))returntrue;if(falseValues.includes(lowerVal))returnfalse;throwError(`"${rawValue}" is not a valid${promptConfig.type} value`);};returnthis;}

For the above example, the bypass function takes the user's text input and turns it into aBoolean value that will be used as the prompt answer data.

Adding Bypass Support to Your Plopfile

If the 3rd party prompt plugin you are using does not support bypass by default, you can add thebypass function above to your prompt's config object and plop will use it for handling bypass data for that prompt.

Wrapping Plop

Plop provides a lot of powerful functionality "for free". This utility is so powerful, in fact, that you can even wrapplopinto your own CLI project. To do so, you only need aplopfile.js, apackage.json, and a template to reference.

Yourindex.js file should look like the following:

#!/usr/bin/env nodeimportpathfrom"node:path";importminimistfrom"minimist";import{Plop,run}from"plop";constargs=process.argv.slice(2);constargv=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));

And yourpackage.json should look like the following:

{"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"  }}

Setting the base destination path for the wrapper

When wrapping plop, you might want to have the destination path to be based on the cwd when running the wrapper. You can configure thedest base path like this:

Plop.prepare({// config like above},env=>Plop.execute(env,(env)=>{constoptions={            ...env,dest:process.cwd()// this will make the destination path to be based on the cwd when calling the wrapper}returnrun(options,undefined,true)}))

Adding General CLI Actions

Many CLI utilities handle some actions for you, such as runninggit init ornpm install once the template is generated.

While we'd like to provide these actions, we also want to keep the core actions limited in scope. As such, we maintain a collection of libraries built to add these actions to Plop inour Awesome Plop list. There, you'll be able to find options for those actions, or even build your own and add it to the list!

Further Customization

Whileplop provides a great level of customization for CLI utility wrappers, there may be usecases where you simplywant more control over the CLI experience while also utilizing the template generation code.

Luckily,node-plop may be for you! It's what theplop CLI itself is builtupon and can be easily extended for other usage in the CLI. However, be warned, documentation is not quite as fleshed outfor integration withnode-plop. That is to sayThar be dragons.

We note lackluster documentation onnode-plop integration not as a point of pride, but rather a word of warning.If you'd like to contribute documentation to the project, please do so! We always welcome and encourage contributions!


[8]ページ先頭

©2009-2025 Movatter.jp