Is it possible to add multiple files with single templateFile in PLOP

1.4k views Asked by At

I am using plop dependancy to generate module. I want to generate n number of files in one go that used single template.

plop.setGenerator('module', {
  description: 'Create a module',
  // User input prompts provided as arguments to the template
  prompts: [
    {
      // Raw text input
      type: 'input',
      // Variable name for this input
      name: 'name',
      // Prompt to display on command line
      message: 'What is your module name?'
    }
  ],
  actions: [
    {
      // Add a new file
      type: 'addMany',
      // Path for the new file
      destination: 'src/Screens/{{pascalCase name}}',
      // Handlebars template used to generate content of new file
      templateFiles: 'plop-templates/**.js.hbs'
    }
  ]
})
2

There are 2 answers

0
Hamza Zaidi On

wrap templateFiles in the array.

templateFiles: ['plop-templates/**.js.hbs']
0
silicakes On

For anyone interested, here's how I got this working

const page = {
  description: "⚛ react page",
  prompts: [
    {
      type: "input",
      name: "names",
      message: "page name",
    },
  ],
  actions: (data) => {
    const names = data.names.split(/\s+/).map((name) => name.trim());
    return names.flatMap((name) => {
      return [
        {
          type: "add",
          path: `../src/pages/{{pascalCase name}}/{{pascalCase name}}.tsx`,
          templateFile: "./templates/page.tsx.hbs",
          data: { name },
        },
        {
          type: "add",
          path: "../src/pages/{{pascalCase name}}/{{pascalCase name}}.test.tsx",
          templateFile: "./templates/test.tsx.hbs",
          data: { name },
        },
      ];
    });
  },
};

const generator = (plop) => {
  plop.setDefaultInclude({ generators: true });
  plop.setGenerator("page", page);
};

export default generator

syntax:

$ plop page page1,page2,page3

✔  ++ src/pages/Page1/Page1.tsx
✔  ++ src/pages/Page1/Page1.test.tsx
✔  ++ src/pages/Page2/Page2.tsx
✔  ++ src/pages/Page2/Page2.test.tsx
✔  ++ src/pages/Page3/Page3.tsx
✔  ++ src/pages/Page3/Page3.test.ts

Unfortunately plop doesn't play nicely with spaces so you can't pull it off using it. I chose commas instead