Skip to content

How to use templates? #15

@Akiyamka

Description

@Akiyamka

I mainly use once generated modules like this:
template.js

import React from 'react';
import PT from 'proptypes';
import cn from 'classnames';
import style from './style.css';

export default function {componentName}({ className }) {
  return <div className={cn(className, style.root)}></div>
}

{componentName}.propTypes = {
  className: PT.string
}

If I need replace {componentName} i can use make something like this.

  .useHooks('suddenly/cant/use/answers/here', (answers) => [
    useCustom({
      regex: /{moduleName}/,
      content: answers.moduleName,
    })
  ])

But it more complicated cases (replace more the one variable, print something conditionally, use iteration) it can be difficult do only with regexp .

I suggest adding the ability to use the (template literals)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals].
All variables must be available in template scope.
For example:
template file must contain special extention tmpl.js end export function:

module.tmpl.js

module.exports = answers => (
`
import React from 'react';
import PT from 'proptypes';
import cn from 'classnames';
import style from './style.css';
${answers.libs.map(lib => `import ${lib.name} from ${lib.path}` )}

export default function ${answers.moduleName}({ className }) {
  return <div className={cn(className, style.root)}>
    ${ answers.language === 'ru' ? 'Здарова мир' : 'Hello world' }
  </div>
}

 ${answers.moduleName}.propTypes = {
  className: PT.string
 }

`)

And run it when module .move()

cliOf('Create module', module)
  .ask({
    name: 'moduleName',
    message: 'How we name it?',
    type: 'input'
  })
  .move(['./module.tmpl.js], './src/modules/)

or we can add method write that can just write string in file, it more transparent and simpler but in that case we need manually require or import every template

const { cliOf } = require('@recli/cli');
const moduleTemplate = require('./templates/module.tmpl.js');

cliOf('Create module', module)
  .ask({
    name: 'moduleName',
    message: 'How we name it?',
    type: 'input'
  })
  .write([ answers => moduleTemplate(answers) ], './src/modules/module/index.js')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions