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

Nim 完全指南 / 14 模块与包管理

第 14 章:模块与包管理

14.1 模块基础

Nim 的每个 .nim 文件都是一个模块。模块名即文件名(不含扩展名)。

14.1.1 import

# 导入整个模块
import std/strutils
echo "hello".toUpper()  # HELLO

# 导入多个模块
import std/[strutils, sequtils, math]

# 选择性导入
from std/strutils import parseInt, parseFloat
echo parseInt("42")

# 重命名导入
import std/strutils as su
echo su.toUpper("hello")

# 导入但不使用 export
import std/tables except Table, initTable

14.1.2 export

# utils.nim
proc add*(a, b: int): int = a + b  # * 后缀表示导出
proc helper(a, b: int): int = a - b  # 不导出(私有)

# main.nim
import utils
echo add(1, 2)    # ✅ 可用
# echo helper(1, 2)  # ❌ 不可用

# 重新导出
# reexport.nim
import utils
export utils  # 重新导出 utils 的所有公开符号

14.2 包(Package)结构

标准包结构

mypackage/
├── src/
│   ├── mypackage.nim          # 主模块(入口)
│   └── mypackage/
│       ├── submodule1.nim     # 子模块
│       ├── submodule2.nim
│       └── private/
│           └── internal.nim   # 内部实现
├── tests/
│   ├── test_submodule1.nim
│   └── test_submodule2.nim
├── docs/
├── mypackage.nimble           # 包描述文件
├── config.nims                # 项目配置
└── README.md

mypackage.nimble

[Package]
name = "mypackage"
author = "Your Name"
description = "A useful Nim package"
version = "0.1.0"
license = "MIT"
srcDir = "src"
binDir = "bin"

[Deps]
requires "nim >= 2.0.0"
requires "jester >= 0.5.0"

14.3 nimble 包管理器

14.3.1 常用命令

# 创建新包
nimble init mypackage

# 安装依赖
nimble install

# 安装特定包
nimble install jester
nimble install "jester >= 0.5.0"

# 卸载
nimble uninstall jester

# 列出已安装
nimble list --installed

# 搜索包
nimble search json

# 开发模式安装
nimble develop

# 运行任务
nimble test
nimble build

14.3.2 依赖管理

# mypackage.nimble
requires "nim >= 2.0.0"
requires "jester >= 0.5.0, < 1.0.0"
requires "norm"               # 最新版
requires "https://github.com/user/repo.git"  # Git 仓库
requires "localpkg"           # 本地包(通过 nimble develop)

14.3.3 nimble 任务

# 在 .nimble 文件中定义任务
task test, "Run the tests":
  exec "nim c -r tests/test1.nim"

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

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

14.4 路径配置

config.nims

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

# 设置版本号
const Version = "1.0.0"
switch("define", "version=" & Version)

nim.cfg

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

14.5 实战示例

🏢 创建并发布一个包

# 1. 初始化
nimble init mylib -y

# 2. 编写代码
# src/mylib.nim
# src/mylib/utils.nim

# 3. 编写测试
# tests/test_utils.nim

# 4. 测试
nimble test

# 5. 发布
nimble publish

本章小结

功能语法
导入import module
选择性导入from module import symbol
重命名import module as m
导出proc name*() (后缀 *)
创建包nimble init
安装依赖nimble install
运行任务nimble taskname

练习

  1. 创建一个包并添加子模块
  2. 配置 nimble 任务自动化测试和构建
  3. 使用 nimble develop 链接本地开发的包

扩展阅读


上一章:错误处理 | 下一章:文件与 I/O