guybedford / chomp

'JS Make' - parallel task runner for the frontend ecosystem with a JS extension system.
https://chompbuild.com
Apache License 2.0
138 stars 7 forks source link

Templates #5

Closed guybedford closed 2 years ago

guybedford commented 2 years ago

Templates would allow defining a way to generate parameterized tasks. For example, a Svelte template might look like (based on using engines https://github.com/guybedford/chomp/issues/4):

[[template]]
  name = "svelte"
  [[template.option]]
    name = "indir"
    prompt = "Enter input directory"
    default = "src"
    type = "string"
  [[template.option]]
    name = "outdir"
    prompt = "Enter output directory"
    default = "lib"
    type = "string"
  [template]
    generate = """({ outdir, indir }) => [{
      name: 'build:svelte',
      target: `${outdir}/#.svelte.js`,
      deps: [`${indir}`],
      engine: 'node',
      run: `
        import { readFileSync, writeFileSync } from 'fs';
        import { compile } from 'svelte/compiler';

        const source = fs.readFileSync(process.env.dep, "utf-8");
        const result = svelte.compile(source, {
          filename: process.env.DEP,
          css: false,
        });

        writeFileSync(process.env.TARGET, result.js.code);
        writeFileSync(process.env.TARGET + ".map", JSON.stringify(result.js.map));

        const cssFile = process.env.TARGET.replace(/\\.js$/, ".css");
        writeFileSync(cssFile, result.css.code);
        writeFileSync(cssFile + ".map", JSON.stringify(result.css.map));
      `
    }]
    """

With the template "installed", one could then write a task like:

[[task]]
  name = "build:svelte"
  template = "svelte"
  [task.args]
    indir = "src"
    outdir = "lib"
    dev = true

where the target and dependency configuration would be automatically managed based on the provided template input.

Internally, the template is expanded based on the options provided, with the template generation itself running as an embedded JS engine like QuickJS or similar.

The inner "run" via engines still runs in Node.js though!

This means the template can be very quickly expanded without needing to spawn an external process and internally turned into its expanded task form.

When initializing the template to begin with, the prompt definitions allow for nice standard CLI prompts for setting template options. Possibly even via a visual tool in future.

guybedford commented 2 years ago

Templates implemented in https://github.com/guybedford/chomp/commit/5e69aa1bbbe11a29156259de4c84e6818051ecd0.