Creating dotnet new templates with samples
In this post I will show the needed steps and samples to create dotnet new templates.
Introduction
Recently a friend asked me about the steps I follow to create dotnet new templates, while I was describing the steps to him I realized that information could be usefull to someone else or even to my future self.
Sometime ago I created some dotnet new templates for GeneticSharp: dotnet new templates for GeneticSharp and I will use that template as samples for the steps below.
Nuget pack / dotnet pack
Nowadays there are two main ways to build a dotnet new template: creating a .nuspec file or defining the package properties directly inside your .csproj.
To GeneticSharp templates I used a .nuspec.
Steps and samples
When I was trying to create the first templates I used this Microsoft documentation to learn about it: Custom templates for dotnet new.
Creating
- Create a
Templatesfolder: sample - Define the templates in the
.csprojor create a.nuspec: sample - Create a
contentfolder inside theTemplatesfolder: sample - Create a subfolder inside
contentfor each template and put your template project source code there: sample - For each template folder, create a subfolder
template.configthen create atemplate.jsonfile: sample
In this .json you should define things like template name (shortName) and what it’s root namespace that will be replaced when a new project use this template (sourceName)
Building and testing
- Now you can create the
.nupkgwith thedotnet packornuget pack - You can test your templates locally installing them directly from the
.nupkgfile:dotnet new -i your_templates_file.nupkg - Install the template:
dotnet new template_shortname -n new_project_namespace -o output_folder
Here a .cmd sample for last 3 steps: sample
Publishing
- If everything is right you can publish your
.nupkgon http://nuget.org or to your private NuGet feed: sample
Conclusion
That’s it, with just 9 steps you can create your own dotnet new template and jumpstart your next project setup.