Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Interop and Tooling

Projects, Packages and the dotnet CLI

Learn the F# project workflow: dotnet new, the fsproj file and compile order, NuGet packages, solutions, F# Interactive and .fsx scripts, #r references, formatting with Fantomas and publishing.

Writing F# in a file is the easy part. Real work needs a project: dependencies, a build, tests, a way to run and ship. The good news is that F# uses the same dotnet command-line tool as C#, so everything here works the same on Windows, macOS and Linux and in any editor (Visual Studio, VS Code with Ionide, JetBrains Rider).

The dotnet CLI

Terminal
dotnet new console -lang F# -o HelloFs     # create a console app
cd HelloFs
dotnet run                                 # build and run
dotnet build                               # build only
dotnet test                                # run tests (in a test project)
dotnet add package FsToolkit.ErrorHandling # install a NuGet package
dotnet publish -c Release                  # produce deployable output

Other useful templates: classlib (library), xunit or nunit (tests), web (minimal ASP.NET Core), sln (solution file). Use dotnet new list to see them all and -lang F# to pick the F# variant.

The project file

An F# project is a .fsproj (XML) file:

XML
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Domain.fs" />
    <Compile Include="Logic.fs" />
    <Compile Include="Program.fs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="FsToolkit.ErrorHandling" Version="5.0.0" />
  </ItemGroup>

</Project>

Two things stand out compared with C#:

  1. <Compile Include> is explicit and ordered. F# compiles files from top to bottom, and each file can use only what the files above it define. Domain.fs (types) comes first, Program.fs (the entry point) last. A cyclic dependency is impossible, which keeps architecture clean. If you get "The value or constructor is not defined", the first thing to check is file order. Ionide and Visual Studio let you move a file up or down in the project tree.
  2. The last file is the entry point. Its final top-level expression, or a function marked [<EntryPoint>], runs first:
FSHARP
module Program

[<EntryPoint>]
let main argv =
    printfn "Hello %s" (if argv.Length > 0 then argv.[0] else "world")
    0     // exit code

A file without [<EntryPoint>] as the last file of an exe runs its top-level statements instead (the common script style).

TreatWarningsAsErrors is worth enabling on day one, because incomplete pattern matches are warnings, not errors. A finer option is <WarnOn>25</WarnOn> and <WarningsAsErrors>FS0025</WarningsAsErrors> for only that case.

Namespaces and modules

Each file starts with a namespace or a top-level module:

FSHARP
namespace MyApp.Domain

type Customer = { Id: int; Name: string }

module Customer =
    let create id name = { Id = id; Name = name }

A type and a module with the same name can coexist; the module gets a hidden Module suffix at compile time unless you mark the type with [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] (implicit since F# 4.1). This is the standard way to attach functions to a record or union: Customer.create 1 "Ada".

C# C# stand-in: the same split of type and functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

NuGet packages

Packages are added with dotnet add package <name> (or edited into PackageReference). Useful F#-friendly ones:

  • FSharp.Core (always included): the standard library.
  • FsToolkit.ErrorHandling: result, option and validation workflows.
  • Giraffe / Falco: functional web frameworks on ASP.NET Core.
  • Thoth.Json / FSharp.SystemTextJson: JSON with unions and options.
  • Expecto, xUnit, FsUnit, FsCheck: testing (Testing F# Code).
  • Fantomas: the standard code formatter (dotnet tool install -g fantomas, then fantomas .).

Use dotnet list package --outdated to see updates and keep package versions pinned in the project or in Directory.Packages.props for central management.

F# Interactive and scripts

dotnet fsi starts F# Interactive (FSI), a REPL. Type an expression ending in ;; and it evaluates:

TEXT
> let square x = x * x;;
val square: x: int -> int

> square 7;;
val it: int = 49

The REPL also runs script files with the .fsx extension, where you can pull in packages directly:

FSHARP
#r "nuget: Newtonsoft.Json, 13.0.3"

open Newtonsoft.Json

let json = JsonConvert.SerializeObject {| name = "Ada"; age = 36 |}
printfn "%s" json

Run it with dotnet fsi script.fsx. #load "Other.fsx" includes another script and fsi.CommandLineArgs holds the arguments. Scripts are perfect for experiments, one-off data jobs and teaching; when they grow, move the code into a project and keep .fsx as a thin driver. Many F# developers explore ideas in FSI first and copy the finished functions to a file.

flowchart LR
    A["Idea"] --> B["FSI / .fsx script"]
    B --> C["Library project<br/>.fsproj"]
    C --> D["Tests"]
    C --> E["Console or web app"]
    E --> F["dotnet publish"]

A typical path from experiment to shipped application.

Formatting, analysis and warnings

Run Fantomas to end formatting debates (indentation is significant in F#, so a consistent style matters). FSharpLint and the compiler's warnings catch smells. Turn on --warnon:3390 (XML doc checking) in library projects and treat the important warnings (incomplete matches, unused values, nullness) as errors in CI.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command creates a new F# console project?

    dotnet new with the console template and -lang F# scaffolds the project.
  2. 2. Why does the order of <Compile Include> entries matter?

    F# compiles files in order, which prevents circular dependencies.
  3. 3. How do you reference a NuGet package inside an .fsx script?

    The #r "nuget: ..." directive downloads and references a package in F# Interactive.
  4. 4. What is the tool most F# projects use to format code?

    Fantomas is the de-facto standard F# formatter.

Summary

  • The dotnet CLI creates, builds, tests, runs and publishes F# projects.
  • The .fsproj lists files in compile order; the last file holds the entry point.
  • Put types and their functions in same-named type and module pairs.
  • Add libraries with dotnet add package; FSI and .fsx scripts reference packages with #r "nuget: ...".
  • Use Fantomas for formatting and treat important warnings as errors.

Next: Testing F# Code