跳到主要内容

MoonBit 构建系统教程

Moon是MoonBit语言的构建系统,目前基于n2项目。Moon支持并行和增量构建本地包。管理和构建第三方包的功能即将推出。

先决条件

在开始本教程之前,请确保已安装以下内容:

  1. MoonBit CLI工具: 从这里下载。这个命令行工具用于创建和管理MoonBit项目。

    使用moon help命令查看使用说明。

    $ moon help
    Moonbit's build system

    Usage: moon <COMMAND>

    Commands:
    build Build the current package
    check Check the current package, but don't build object files
    run Run WebAssembly module
    clean Remove the target directory
    new Create a new moonbit package
    bench Generate build matrix for benchmarking
    fmt Format moonbit
    version Print version info and exit
    help Print this message or the help of the given subcommand(s)

    Options:
    -h, --help Print help
  2. Moonbit Language Visual Studio Code 插件: 可以从VS Code市场安装。该插件为MoonBit提供了丰富的开发环境,包括语法高亮、代码补全等功能。

完成这些先决条件后,让我们开始在MoonBit中构建一个新模块。

创建一个新模块

要创建一个新模块,在终端中输入moon new hello命令:

$ moon new hello

该命令将创建一个名为hello的新模块。

理解模块目录结构

创建新模块后,目录结构应如下所示:

.
├── lib
│ ├── hello.mbt
│ └── moon.pkg
├── main
│ ├── main.mbt
│ └── moon.pkg
└── moon.mod

这里对目录结构进行简要解释:

  • libmain目录:这些是模块中的包。每个包可以包含多个.mbt文件,这些文件是MoonBit语言的源代码文件。不过,无论包中有多少个.mbt文件,它们都共享一个公共的moon.pkg文件。

  • moon.pkg文件:包描述符文件。它定义了包的属性,例如包的名称和导入的包。

  • moon.mod用于将目录标识为MoonBit模块。它包含模块的名称:

    ./moon.mod
    module "hello"

检查项目

使用Visual Studio Code打开项目。在安装了MoonBit插件之后,在终端中使用moon check --watch命令自动检查项目。

before watch

执行moon check --watch之后,VS Code应该如下所示。

after watch

使用包

我们的hello模块包含两个包:libmain

lib包含一个hello.mbt文件:

./lib/hello.mbt
pub func hello() -> String {
"Hello, world!\n"
}

main包含一个main.mbt文件:

./main/main.mbt
func init {
@lib.hello().print()
}

要执行您的程序,请指定路径到main包:

$ moon run ./main
Hello, world!

包导入

在MoonBit的构建系统中,模块的名称用于引用其内部包。 要在main/main.mbt中导入lib包,需要在main/moon.pkg中指定:

./main/main.pkg
package main

import "hello/lib"

这里,import "hello/lib"指定要导入hello模块中的lib包。

创建和使用包

要创建一个新的包,在模块目录中使用moon newpkg命令,并指定包的名称。例如,要创建一个名为utils的新包,执行以下命令:

$ moon newpkg utils

这将在模块目录中创建一个名为utils的新包,并在utils目录中添加一个.mbt文件和一个moon.pkg文件。

现在,您可以在其他包中导入和使用utils包。例如,假设您在lib/hello.mbt中想要使用utils包:

./lib/hello.mbt
import "hello/utils"

pub func hello() -> String {
let currentTime = utils.getTime()
"Hello, world! The current time is " + currentTime + "\n"
}

然后,在utils包的.mbt文件中实现getTime函数:

./utils/utils.mbt
pub func getTime() -> String {
let time = // implementation to get current time
// format the time if necessary
time
}

注意:在上面的示例中,utils包是相对于hello模块的导入路径。如果在不同的模块中使用utils包,需要相应地更改导入路径。

使用moon run命令运行程序,MoonBit将自动解析和构建包之间的依赖关系。

$ moon run ./main
Hello, world! The current time is 2023-08-30 10:00 AM

这样,就可以创建新的包并在其他包中使用它们了。

总结

这是一个简要的MoonBit构建系统教程,希望它能帮你入门MoonBit并开始构建自己的模块。你可以通过阅读MoonBit的文档和探索更多示例来进一步学习和了解MoonBit构建系统的功能和特性。祝你在MoonBit的旅程中取得成功!