jondot / hygen

The simple, fast, and scalable code generator that lives in your project.
http://www.hygen.io
MIT License
5.65k stars 253 forks source link

feat: dynamic localsDefaults #424

Open francoislevesque opened 1 year ago

francoislevesque commented 1 year ago

Context

We want to dynamically inject new variables to the locals object depending on the user's input. This is useful for several reasons.

  1. We want to automatically generate variations of an argument to lighten the templates' code. a. For exemple, if a user inputs --name 'OrderLine', we want to dynamically add :

    • myName : "orderLine"
    • my_name : "order_line"
    • MyName : "OrderLine"
    • myNameS : "orderLines" (forced plural)
    • my_nameS : "order_lines" (forced plural)
    • MyNameS : "OrderLines" (forced plural)

    This allows us the replace the following code :

    // less lisible
    let <%= h.camelCase(h.plural(model)) %>
    
    // increased lisibility
    let <%= myNameS %>
  2. We can add dynamic variables depending of the user arguments. Internally, we built a 20 field type generators (for input text, select, date picker, autocomplete, etc). Depending on the given field type, we want to make new variables accessible in the template. We prefer this approach over helpers because it makes the code a bit more readable, but also a lot faster. We use complex helpers to add dynamic variables available to the templates, but these are recalculated everytime they are called. Having more than 200 templates, this will greatly improve DX and performance!

How to use

// .hygen.js

module.exports = {
  templates: `${__dirname}/.hygen/templates`,
  localsDefaults(locals, config) {
    return {
      myModel: changeCase.camelCase(locals.model ?? ""),
    };
  },
}