preface

I believe that in our daily encountered projects, whether in the front-end website or background management system will have similar functions of the page. When we develop these pages with similar functions, in order to improve efficiency, we generally use our CV method. But when we CV for a long time, will not feel that such a way of development is a little boring? Can we further improve our efficiency by generating code from code? Let’s use an example to explore how node generates the front-end code we need.

The instance

The react file directory structure is as follows:

Under the Page folder there are two folders, home and Network, which represent different modules. After a brief inspection, it is not hard to see that the file directory structure under the two modules is the same, and some of the file names are the same. Some people, including me at the beginning of the project, might look at this situation and think, CV, easy and quick. But this time, let’s take a look at the initial code needed in the JS file:

The structure is basically the same, but the names of modules and components are different.

In the above in this case, we can be of similar folders and files to copy and paste, but we also need to rename for different components, modules and operation, such as page file also to say less, but when the page is more, such as the seven or eight modules and dozens of pages, we do these meaningless repetition operation, Will it be uncomfortable?

So can we figure out a way to avoid these operations as much as possible?

Coach Lue: The way? Pass the ball to Lebron, of course!

Just kidding. First of all, we should carefully analyze the files under Pages, home and network folders have the same file directory structure, but some folders under the file name and content may be different. This is somewhat similar to the reuse of components, so can we use the idea of similar reuse of components, write a unified template, and then pass different parameters to it, so different components can be generated.

The basic idea is as follows:

Through the form of configuration parameters to configure our folder name, file name and file template parameters, and then one click to generate our folder, file and file content.

node API

The basic idea is sure, but how do we automatically generate folders and files? I believe that the back-end partners are certainly not unfamiliar, while the front-end partners may be less involved in this aspect of business knowledge. But once you’re familiar with Node, this shouldn’t be a problem.

Here we can use Node’s FS (file system) API to help us do this.

Create a directory

There are two ways to create file (directory) folders in Node:

Fs.mkdir (path[, options], callback)

parameter

  • Path – File path.
  • The options parameter can be:
    • Recursive – Whether to create directories recursively. Default is false.
    • Mode – Sets directory permissions. The default is 0777.
  • Callback – A callback function with no arguments.

Basic usage

fs.mkdir('/pages/home', (err) => {
  if (err) throw err;
});
Copy the code

Second (synchronization) : fs.mkdirsync (path[, options])

Basic usage

fs.mkdirSync('/pages/home');
Copy the code

Create a file

There are also two ways to create files:

Fs.writefile (file, data[, options], callback)

parameter

  • File – File name or file descriptor.
  • Data – The data to be written to the file, which can be a String or Buffer object.
  • Options – This parameter is an object containing {encoding, mode, flag}. Default encoding is UTF8, mode is 0666, flag is ‘w’
  • Callback – A callback function that contains only error message arguments (ERR) and returns if a write fails.

Basic usage

fs.writeFile('file. TXT'.'how are you ~', (err) => {
  if (err) throw err;
  console.log('File has been saved');
});
Copy the code

Second (synchronous) : fs.writefilesync (file, data[, options])

Basic usage

fs.writeFileSync('file. TXT'.'how are you ~');
Copy the code

Generate directories and files

Now that we know the basics, we can write the code. Of course, the computer needs to have a Node environment, generally speaking, we should configure the Node environment, if there is no online search on the OK ~

Create project documentation

First set up our project:

Focus on the folders and files in the red box

  • index.jsThe program logic generated for our main program, folders (directories) and files is all in there, which is also the final file to run
  • Pages generates folders (directories) and files for us
  • Template contains two files
    • data.jsFor our configuration file, including folder (directory) and file name and file template parameters configuration
    • template.jsTemplates for our various files

Here, we assume that we are in the React project, so the other files are basically react related. The code logic in the red box is decoupled from react and applies to other frameworks as well.

Generate folders (directories)

Going back to the original example, we need to generate folders and files in the pages folder in the following format:

Fs.mkdir () or fs.mkdirsync () are created on an existing folder. For example, if we want to create a list folder under Pages, we cannot write:

index.js

const fs = require("fs");
fs.mkdirSync('./page/home/list'); / / an error
Copy the code

Since the home folder does not exist, the list folder will not be created. The correct way to write this is:

const fs = require("fs");
fs.mkdirSync('./page/home'); 
fs.mkdirSync('./page/home/list');
Copy the code

Of course, we can’t write this directly. We can create the directory recursively:

index.js

const fs = require("fs");
const path = require("path");

function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) { // Check whether the file directory already exists
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return console.log('Directory created successfully -${dirname}`);
        }
    }   
}
mkdirsSync('./page/home/list');
Copy the code

Next is the configuration file:

data.js

exports.data = [
    {
        folder:'home'}, {folder:'home/list'}, {folder:'home/images'
    },
    {
        folder:'home/form'}, {folder:'network'}, {folder:'network/list'}, {folder:'network/images'
    },
    {
        folder:'network/form',}]Copy the code

Import the configuration file and walk through the build file:

index.js

const fs = require("fs");
const path = require("path");
// Import the configuration file
const profileData = require("./template/data");
// Create a directory synchronization method recursively
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return console.log('Directory created successfully -${dirname}`); }}}// Iterate through the configuration file and call the create directory method
profileData.data.forEach((item) = > {
    if(item.folder){
        mkdirsSync(`./pages/${item.folder}`)}})Copy the code

Generate the file

We’ve generated the directory, and we’re just going to focus on the filename and the content of the file when we generate the file. First we need to define the template of the file, here we mainly use the template string (‘). Because some of the file contents have different class names, you can define a parameter for this type of template when defining the template, as shown in className:

template.js

exports.page = function (className) {
    return `
import * as React from 'react';

export class ${className} extends React.Component{
    constructor(props){
        super(props);

        this.state = {}
    }

    componentDidMount(){

    }

    render() {
        return (
            <div></div>
        )
    }
}
    ` 
}

exports.api = `const API = "localhost://8080/my-api"; `

exports.route = ` import * as React from 'react'; export const route = []; `
Copy the code

After the template is defined, continue to add the corresponding a configuration item to the configuration file data.js, as shown in file and className:

data.js

exports.data = [
    {
        folder:'home'.file:'api.js'
    },
    {
        folder:'home'.file:'route.js'
    },
    {
        folder:'home/list'.file:'home.js'.className:'Home'
    },
    {
        folder:'home/images'
    },
    {
        folder:'home/form'.file:'modal.js'.className:'homeModal'
    },
    {
        folder:'network'.file:'api.js'}, {folder:'network'.file:'route.js'
    },
    {
        folder:'network/list'.file:'network.js'.className:'Network'
    },
    {
        folder:'network/images'
    },
    {
        folder:'network/form'.file:'modal.js'.className:'networkModal'}]Copy the code

Finally, the file generation code is written:

index.js

const fs = require("fs");
const path = require("path");
// Import the configuration file
const profileData = require("./template/data")
// Import the file template
let template = require("./template/template");
let page = template.page;
let api = template.api;
let route = template.route;


// iterate over the create file
profileData.data.forEach((item) = > {
    if(item.file){
        // Create an API file
        if(item.file.indexOf("api") != - 1){
            fs.writeFile(`./pages/${item.folder}/${item.file}`, api, function(err){
                if(err){
                    return console.log('Creation failed', err);
                }
                console.log('File created successfully! -${item.file}`); })}// Create a route file
        if (item.file.indexOf("route") != - 1){
            fs.writeFile(`./pages/${item.folder}/${item.file}`, route, function(err){
                if(err){
                    return console.log('Creation failed', err);
                }
                console.log('File created successfully! -${item.file}`); })}// Create the body page
        if (item.className){
            fs.writeFile(`./pages/${item.folder}/${item.file}`, page(item.className), function(err){
                if(err){
                    return console.log('Creation failed', err);
                }
                console.log('File created successfully! -${item.file}`); }}}})Copy the code

Finally, we can run index.js directly:

We can see that the console prints a message indicating that we have successfully created folders (directories) and files. Finally, we can look at the directories and files under the Pages folder:

We can compare the directories and files to the files in the initial instance and see that we have successfully generated the desired directories and files

Done ~

I have put the complete code and examples on my GitHub, and friends can modify them according to their actual needs to improve their development efficiency.

reference

www.runoob.com/nodejs/node…

nodejs.cn/api/fs.html

The last

The above method of file configuration and template invocation automatically generates duplicate code files. This way to a certain extent can reduce our copy and paste repetitive labor, improve our work efficiency. This way is also one of my attempts in development, which still has many shortcomings. If you have tried to improve your development efficiency in your work, please share with us

If there are any mistakes in this article, please feel free to mention them