0

I am working on a CLI that bootstraps a project depending on what dependencies you select you want. I need to conditionally inject certain parts into a tsx file at build time, but I dont want any trace of it in the bootstrapped project.

What I want is a transform like this:

// index.template.tsx
import x from "x";
{{importSection}}

export const Foo = () => {
  {{usageSection}}
  return <div>{{renderSection}}</div>;
}

// transforms at build time to (based on some config)
// index.tsx
import x from "x";
import y from "y";

export const Foo = () => {
  const data = y.usageOfY();
  return <div>{data.hello}</div>;
}

// but sometimes just remove the template literals (based on the config)
// index.tsx
import x from "x";

export const Foo = () => {
  return <div></div>;
}

I will invoke the transform from a Node.js script such as:

const installer = () => {
  if (x) 
    transform({
      importSecion: `import y from "y";`
      usageSection: `const data = y.usageOfY();`
      renderSection: `{data.hello}`
    })
  else
    transform()
}
I have taken a look Handlebars and jscodeshift but struggle to understand if they are suited for this.
Julius
  • 31
  • 4
  • `sed` could do this for you, even, is there a specific issue you're struggling with? As a side note, I would recommend turning your insertion points into comments so your source pre-transform is still valid so you can use all tooling you may have. – Etheryte Jun 20 '22 at 09:44
  • @Etheryte Yes, for a simple example like this a simple find and replace would do, but I anticipate running into more complex situation so that's where I see the benefits of using a templating solution like Handlebars but I am unsure if it can do what I want or if there is another option out there – Julius Jun 20 '22 at 12:19

0 Answers0