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

How to template dynamically generated react code?

user6084
1#
user6084 Published in September 21, 2018, 8:04 am

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?

share|improve this question

1 Answer 1

active oldest votes
up vote 0 down vote accepted
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO