Essay - Published: 2022.10.26 | command-line | dotnet | fsharp |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
In this post, we'll create a new F# project from the command line.
We'll walk through creating two different kinds of apps:
We'll be using the official dotnet CLI tool which will get you set up with a lean, up-to-date project skeleton to start building with F#.
.NET SDK - The only thing we need for this tutorial is the .NET SDK installed on your machine which will give us access to the dotnet command.
First let's create a console application. This is typically the simplest kind of application - it's invokable via command line, it runs some code, it exits.
Create a console app command:
dotnet new console -lang f#
This will create a project with a few files:
YOUR_APP_NAME.fsproj - This contains metadata about your project like what files to include and what dependencies it has. This is similar to a package.json in javascript / npmProgram.fs - This is your "main" file. This will be run like a script, top-to-bottom.obj/ - This contains build artifacts, you'll typically want to .gitignore thisMy Program.fs looks like this:
Program.fs
printfn "Hello from F#"
We can run it with:
dotnet run
When I run this, it outputs:
Hello from F#
More resources:
Console apps are useful, but typically you'll want to write something that's invokable via the web. The standard framework for web in F# / .NET land is ASP.NET base with optional frameworks built on top.
Covering all web options is out of scope for this post but you can get started with sane defaults using CloudSeed - a fullstack F# project boilerplate - and see a list of officially endorsed options in Web Programming with F#
Create a web project command:
dotnet new web -lang f#
This will create a project with a few files:
YOUR_APP_NAME.fsproj - (Same as console app) A file listing metadata about your project and how to build itProgram.fs - A simple main function that initializes ASP.NET, creates a minimal API endpoint at / that returns Hello World!, then starts the serverProgram.fs
open System
open Microsoft.AspNetCore.Builder
open Microsoft.Extensions.Hosting
[<EntryPoint>]
let main args =
let builder = WebApplication.CreateBuilder(args)
let app = builder.Build()
app.MapGet("/", Func<string>(fun () -> "Hello World!")) |> ignore
app.Run()
0 // Exit code
We can start the web server with:
dotnet run
This should print some info to console including what port it's listening on. Mine says:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7055
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5127
If I go to the http://* link, I see Hello World! returned from my server.
You should now have a working skeleton for a console app and a web app.
Further reading:
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.