Home How to template dynamically generated react code?
Reply: 1

How to template dynamically generated react code?

JavascriptLoser
1#
JavascriptLoser Published in 2018-02-13 01:20:18Z

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?

Thiago F. Pappacena
2#
Thiago F. Pappacena Reply to 2018-02-13 01:43:03Z

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' });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.297623 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO