Search code examples
javascriptnode.jsreactjstemplates

How to template dynamically generated react code?


I'm currently working on a framework for a web app that a number of developers will be working on. The web app will be in a dashboard style, with individual modules or "views" written in React.

One of the requirements of the framework is that it must ship with a tool that allows developers to automatically generate a new module or "view", so that it creates the files and folders needed and they can get straight to work on the code logic.

An extremely simple flow would be as follows:

  1. Developer enters the name of their new module as an argument to a npm script
  2. A script runs which creates [moduleName.js] and [moduleName.less], links them together, places them in a directory, and writes the generic react code.

I'm now up to the point where I am generating the common react code. Here is what I wrote:

function writeBoilerplate(moduleName) {

var jsFileStream = fs.createWriteStream("./src/m-" + moduleName + "/" + moduleName + ".js");
jsFileStream.once('open', (fd) => {
    jsFileStream.write("import React from \"react\"\;\n");
    jsFileStream.write("import Style from \"\.\/" + moduleName + "\.less\"\;");
    jsFileStream.write("\n");
    jsFileStream.write("\n");
    jsFileStream.write("export default class " + moduleName + " extends React\.Component \{\n");
    jsFileStream.write("\n");
    jsFileStream.write("    constructor\(\) \{\n");
    jsFileStream.write("        super\(\)\;\n");
    jsFileStream.write("    \}\n");
    jsFileStream.write("\n");
    jsFileStream.write("    componentDidMount\(\) \{");
    jsFileStream.write("    \}");
    jsFileStream.write("\}");
    jsFileStream.end();
});

You can immediately see the problem here, and I stopped before going too far. If I continue on this path, the code will become unreadable and unmanageable.

I want to refactor this to use javascript templates. However, I have never used templating before and I am unsure of how to create a template and use it, or if there are any tools to help.

How can I refactor this code to use a template?


Solution

  • You need to use a template library for that. You can try lodash template one, for example: https://lodash.com/docs#template.

    Put your boilerplate in a template file, read it and use something like:

    var compiled = _.template(templateFileContent);
    compiled({ 'moduleName': 'mymodule' });