强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Nim 完全指南 / 02 安装与环境配置

第 02 章:安装与环境配置

2.1 安装 Nim

Nim 推荐使用 choosenim 进行安装和版本管理。choosenim 类似 Rust 的 rustup、Python 的 pyenv,让你轻松切换 Nim 版本。

2.1.1 Linux / macOS 安装

# 方法一:官方安装脚本(推荐)
curl https://nim-lang.org/choosenim/init.sh -sSf | sh

# 方法二:如果网络不好,设置国内镜像
curl https://nim-lang.org/choosenim/init.sh -sSf | sh -s -- -y

安装完成后,choosenim 会自动:

  1. 下载最新稳定版 Nim
  2. 配置 PATH 环境变量
  3. 安装 nimble 包管理器

验证安装:

nim --version
# Nim Compiler Version 2.x.x ...
nimble --version
# nimble v0.x.x ...

2.1.2 Windows 安装

# 方法一:PowerShell 安装
Invoke-RestMethod -Uri https://nim-lang.org/choosenim/init.ps1 -OutFile choosenim.ps1
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
.\choosenim.ps1

# 方法二:使用 scoop 包管理器
scoop install nim

# 方法三:手动下载
# 从 https://nim-lang.org/install.html 下载 zip 包

2.1.3 Docker 安装

# 拉取官方镜像
docker pull nimlang/nim:latest

# 运行交互式容器
docker run -it nimlang/nim:latest nim --version

# 挂载本地目录开发
docker run -it -v $(pwd):/src -w /src nimlang/nim:latest nim c -r main.nim

2.2 版本管理

2.2.1 choosenim 常用命令

# 安装/切换到特定版本
choosenim 2.0.0          # 安装并切换到 2.0.0
choosenim 1.6.14         # 安装并切换到 1.6.14

# 切换到最新稳定版
choosenim stable

# 切换到最新开发版(devel)
choosenim devel

# 查看已安装的版本
choosenim show

# 查看可用版本
choosenim versions

2.2.2 版本对比

版本 特点 推荐场景
stable 最新稳定版 生产开发
2.0.x ORC 默认内存管理 新项目
1.6.x 维护模式,向后兼容 遗留项目
devel 开发版,最新特性 测试新特性

2.2.3 项目级版本锁定

在项目根目录创建 .nimble 文件指定版本:

# myproject.nimble
[Package]
name = "myproject"
version = "0.1.0"
nimVersion = ">= 2.0.0"

2.3 nimble 包管理器

2.3.1 nimble 基础

nimble 是 Nim 的官方包管理器,类似 Python 的 pip、Node.js 的 npm。

# 安装包
nimble install jester        # 安装 Web 框架
nimble install prologue      # 安装另一个 Web 框架
nimble install jsony         # 安装 JSON 库

# 安装特定版本
nimble install [email protected]

# 卸载包
nimble uninstall jester

# 查看已安装的包
nimble list --installed

# 搜索包
nimble search http

# 更新所有包
nimble update
nimble install -d             # 安装项目依赖

2.3.2 创建新项目

# 交互式创建
nimble init myproject

# 直接创建(非交互式)
nimble init myproject -y

生成的项目结构:

myproject/
├── src/
│   └── myproject.nim       # 主源文件
├── tests/
│   └── test1.nim           # 测试文件
├── myproject.nimble         # 项目配置
└── myproject.nimble-link    # 开发链接

2.3.3 nimble 文件详解

# Package
[Package]
name = "myproject"
author = "Your Name"
description = "A Nim project"
version = "0.1.0"
license = "MIT"
srcDir = "src"
binDir = "bin"
bin = "myproject"

# Dependencies
requires "nim >= 2.0.0"
requires "jester >= 0.5.0"
requires "jsony >= 1.1.0"

# Tasks
task test, "Run tests":
  exec "nim c -r tests/test1.nim"

task bench, "Run benchmarks":
  exec "nim c -d:release -r tests/bench.nim"

# Install
skipExt = @["nimble", "nims", "md"]

2.3.4 nimble 任务(Tasks)

# 自定义构建任务
task build_release, "Build release binary":
  exec "nim c -d:release -o:bin/myproject src/myproject.nim"

task build_debug, "Build debug binary":
  exec "nim c --debugger:native -o:bin/myproject_debug src/myproject.nim"

task docs, "Generate documentation":
  exec "nim doc --project --index:on --out:docs src/myproject.nim"

task clean, "Clean build artifacts":
  rmDir "bin"
  rmDir "nimcache"

运行任务:

nimble build_release
nimble test
nimble docs
nimble clean

2.4 IDE 与编辑器配置

2.4.1 VS Code(推荐)

VS Code 是 Nim 开发的最佳选择,配合 Nim Language 扩展使用。

安装步骤:

  1. 安装 VS Code
  2. 打开扩展面板(Ctrl+Shift+X)
  3. 搜索并安装 Nim Language(nim-lang.nim)
  4. 搜索并安装 Nim Language Server(nimsaas.nimlangserver)

推荐的 settings.json 配置:

{
  "nim.nimsuggest.path": "~/.nimble/bin/nimsuggest",
  "nim.lintOnSave": true,
  "nim.lintOnChange": true,
  "nim.checkOnSave": true,
  "[nim]": {
    "editor.tabSize": 2,
    "editor.insertSpaces": true,
    "editor.formatOnSave": true
  },
  "files.associations": {
    "*.nim": "nim",
    "*.nims": "nim",
    "*.nimble": "nim"
  }
}

VS Code 功能一览:

功能 快捷键 说明
自动补全 Ctrl+Space 基于 nimsuggest
跳转定义 F12 跳转到函数/类型定义
查找引用 Shift+F12 查找所有引用
重命名符号 F2 安全重命名
格式化 Shift+Alt+F 使用 nimpretty
运行任务 Ctrl+Shift+B nimble 任务

2.4.2 Neovim / Vim

使用 nvim-treesitternimlsp

-- init.lua 中添加
require'lspconfig'.nimls.setup{
  cmd = { "nimlsp" },
  filetypes = { "nim" },
  root_dir = require'lspconfig'.util.root_pattern("*.nimble", ".git"),
}

安装 nimlsp:

nimble install nimlsp

2.4.3 JetBrains IDEs

安装 Nim 插件:

  1. Settings → Plugins → Marketplace
  2. 搜索 “Nim”
  3. 安装并重启

2.4.4 Emacs

;; 安装 nim-mode
(use-package nim-mode
  :ensure t
  :hook (nim-mode . nimsuggest-mode)
  :config
  (setq nimsuggest-path "~/.nimble/bin/nimsuggest"))

2.5 编译器配置

2.5.1 nim.cfg 全局配置

~/.config/nim/nim.cfg(Linux/macOS)或 %APPDATA%\nim\nim.cfg(Windows)中设置全局编译选项:

# 全局 nim.cfg
--path:"$nim/lib"
--nimcache:"$nimcache"

# 默认开启 ARC 内存管理(Nim 2.0 已默认 ORC)
# --mm:orc

# 开发时常用选项
--colors:on
--showAllMismatches:on

# 并行编译
--parallelBuild:4

2.5.2 项目级 nim.cfg

在项目根目录创建 nim.cfg

# 项目 nim.cfg
--path:"src"
--nimcache:"nimcache"
--hints:on
--warnings:on

2.5.3 config.nims

更灵活的项目配置,支持 Nim 脚本语法:

# config.nims
switch("path", "src")
switch("nimcache", "nimcache")

# 根据构建模式设置
when defined(release):
  switch("opt", "speed")
  switch("checks", "off")
else:
  switch("debugger", "native")
  switch("linedir", "on")

# 设置目标平台
when defined(windows):
  switch("os", "windows")
elif defined(linux):
  switch("os", "linux")

2.6 常用开发工具

2.6.1 nimpretty(代码格式化)

# 格式化单个文件
nimpretty main.nim

# 指定缩进宽度
nimpretty --indent:2 main.nim

# 设置最大行宽
nimpretty --maxLineLen:100 main.nim

2.6.2 nimgrep(代码搜索)

# 搜索符号定义
nimgrep --def "procName" src/

# 搜索用法
nimgrep --use "myFunc" src/

# 普通文本搜索
nimgrep "TODO" src/

# 正则表达式搜索
nimgrep --re "proc \w+" src/

# 忽略大小写
nimgrep --ignoreCase "error" src/

2.6.3 nim doc(文档生成)

# 为单个文件生成文档
nim doc src/mymodule.nim

# 为整个项目生成文档
nim doc --project src/mymodule.nim

# 生成带索引的文档
nim doc --project --index:on --out:docs src/mymodule.nim

2.6.4 nim check(语法检查)

# 仅检查语法,不生成代码
nim check src/main.nim

# 检查整个项目
nim check --project src/main.nim

2.7 环境诊断

如果遇到问题,运行以下命令诊断:

# 查看 Nim 完整配置
nim --dump.format:json --hints:off -e "discard"

# 检查 nimsuggest 是否可用
nimsuggest --version

# 检查 nimble 路径
nimble path

# 查看编译器搜索路径
nim --verbosity:2 --hints:off -e "discard" 2>&1 | grep -i path

2.8 常见问题排查

问题一:nim: command not found

# 检查 PATH
echo $PATH

# 手动添加 PATH(添加到 ~/.bashrc 或 ~/.zshrc)
export PATH=$HOME/.nimble/bin:$PATH

# 重新加载配置
source ~/.bashrc

问题二:nimsuggest 连接失败

# 重新安装 nimsuggest
nimble install nimsuggest

# 检查路径
which nimsuggest

问题三:编译速度慢

# 使用并行编译
nim c --parallelBuild:4 main.nim

# 使用 nimcache
nim c --nimcache:nimcache main.nim

# 增量编译(默认开启)
# 只修改的部分会重新编译

本章小结

工具 用途 安装命令
choosenim 版本管理 curl ... | sh
nimble 包管理 随 Nim 自动安装
nimsuggest IDE 支持 nimble install nimsuggest
nimpretty 代码格式化 随 Nim 自动安装
nimgrep 代码搜索 随 Nim 自动安装

练习

  1. 使用 choosenim 安装 Nim 2.0 最新版和 1.6 最新版,并在两个版本间切换
  2. 使用 nimble init 创建一个新项目,添加 jester 依赖
  3. 配置 VS Code 的 Nim 开发环境,测试自动补全功能
  4. 编写一个 config.nims 文件,配置 release 和 debug 两种构建模式

扩展阅读


上一章:Nim 简介 | 下一章:第一个程序