如何使用Fake构建、打包并发布.NET项目中的类库为NuGet包?
使用Fake工具构建、打包并发布.NET类库为NuGet包的步骤
1. 环境准备
首先确保本地已安装:
- .NET SDK(匹配你的项目目标框架版本)
- Fake CLI工具,通过以下命令安装:
dotnet tool install -g fake-cli
2. 创建Fake构建脚本
在项目根目录新建build.fsx文件,这是构建流程的核心配置文件。
3. 编写脚本核心逻辑
以下是包含清理、构建、打包、发布全流程的示例脚本:
// 引用Fake核心模块 #r "paket: nuget Fake.Core.Target nuget Fake.DotNet.Cli nuget Fake.Core.Environment //" #load ".fake/build.fsx/intellisense.fsx" open Fake.Core open Fake.DotNet open Fake.IO.Globbing.Operators // 基础配置 let solutionPath = "YourSolution.sln" // 替换为你的解决方案路径 let nugetSource = "https://api.nuget.org/v3/index.json" // 可替换为私有源地址 let nugetOutputDir = "./artifacts/nuget" // 清理目标:清理项目输出目录 Target.create "Clean" (fun _ -> DotNet.clean (fun opts -> { opts with Configuration = DotNet.Release OutputPath = Some "./artifacts" }) solutionPath ) // 构建目标:编译类库 Target.create "Build" (fun _ -> DotNet.build (fun opts -> { opts with Configuration = DotNet.Release OutputPath = Some "./artifacts/build" }) solutionPath ) // 打包目标:生成NuGet包 Target.create "Pack" (fun _ -> // 从环境变量读取版本号,避免硬编码 let packageVersion = Environment.environVarOrDefault "PACKAGE_VERSION" "1.0.0" DotNet.pack (fun opts -> { opts with Configuration = DotNet.Release OutputPath = Some nugetOutputDir Version = Some packageVersion NoBuild = true // 依赖Build目标完成编译,跳过重复构建 IncludeSymbols = true // 可选:生成符号包 IncludeSource = true }) // 可选:生成源包 solutionPath ) // 发布目标:推送NuGet包到指定源 Target.create "Publish" (fun _ -> // 从环境变量读取API密钥,禁止硬编码 let nugetApiKey = Environment.environVar "NUGET_API_KEY" // 获取所有生成的NuGet包(排除符号包) let nugetPackages = !! (nugetOutputDir + "/*.nupkg") -- (nugetOutputDir + "/*.symbols.nupkg") nugetPackages |> Seq.iter (fun packagePath -> DotNet.nugetPush (fun opts -> { opts with ApiKey = Some nugetApiKey Source = Some nugetSource SkipDuplicate = true }) // 跳过已存在的包 packagePath ) ) // 设置目标执行顺序:Clean → Build → Pack → Publish open Fake.Core.TargetOperators "Clean" ==> "Build" ==> "Pack" ==> "Publish" // 默认目标:仅执行打包 Target.runOrDefault "Pack"
4. 关键配置说明
- 版本号管理:通过环境变量
PACKAGE_VERSION传递版本号,例如:PACKAGE_VERSION=1.0.1 fake run build.fsx --target Publish - API密钥安全:通过环境变量
NUGET_API_KEY传递密钥,Windows用set NUGET_API_KEY=你的密钥,Linux/macOS用export NUGET_API_KEY=你的密钥 - 私有源适配:替换
nugetSource为你的私有NuGet源地址即可
5. 运行构建命令
- 仅打包:
fake run build.fsx - 完整发布流程:
fake run build.fsx --target Publish
内容的提问来源于stack exchange,提问作者Tom Kerkhove
相关产品推荐
相关产品推荐

