NodeJs Project Generator
Back when I started doing NodeJs development, One of the biggest pains when starting a new project was creating one, and installing all the backbone dependencies that I deem are must haves. Fast forward a couple of years, and I’m back doing some more NodeJs development, but this I was not going to go doen that same rabbit hole. In come templates. In a minute I will show just how easy it is to create your own NodeJs project generator to create projects tuned to your specific needs.
You want to start out by creatingtwo folders, one name generator and another named templates. Our core generator logic will go into the generator folder, and we will create our pre-defined projects in the templates folder.
Create as many project as you’d like in this folder. These will be the projects that you will choose from the command line to create when starting a new project. In this example I created two templates, One plain node and express project, nothing fancy, and another Node and express, but this time using typescript (<3), along with webPack, for all our transpiling needs.
The generator will be reliant on a couple dependencies. The Inquirer package, to interact with the command line, as well as the fs-extra package for file system operations that our generator will be executing.
Lead me master
To start off, you need to ask the developer (You) what project you want to create from a list of choices, these choices are being generated from all the templates you have created in the templates folder. Not just that, but also get the name for the project, and here is how we get those values from the command line, using inquirer
Once we know what we want to create, we can go ahead and copy out the template that we created in our templates folder, into the current directory:
There you go. Go ahead and run node index.js, complete the steps, and a brand new project set to your specifications will be created. What’s that I hear you say? You want to be able to run this command from anywhere on your machine? Ok, let’s do that.
We want to be able to run this command from anywhere on out machine, to do that we’re going to have to install this project.
First, you want to give your project an alias, this is the command you are going to call to start your generator project from the command line. Add the line below to your package.json. “my-templates” whatever you want it to be.
Then add the code below to the top of our index.js file to indicate that this is a node script, and not a shell script.
Once the configuration is out of the way, we can go ahead and globally install our package by running the command npm install –g from the root of our project. Now you can change to any directory, call your named command, follow the prompts, and a new templated project will be created right there.
Thank you for following along, the sample project is available on my github here should you need it for reference.