Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use templates? #15

Open
Akiyamka opened this issue Feb 18, 2020 · 0 comments
Open

How to use templates? #15

Akiyamka opened this issue Feb 18, 2020 · 0 comments

Comments

@Akiyamka
Copy link
Contributor

Akiyamka commented Feb 18, 2020

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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant