MoonBit 构建系统教程
Moon是MoonBit语言的构建系统,目前基于n2项目。Moon支持并行和增量构建本地包。管理和构建第三方包的功能即将推出。
先决条件
在开始本教程之前,请确保已安装以下内容:
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 helpMoonbit 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
这里对目录结构进行简要解释:
lib
和main
目录:这些是模块中的包。每个包可以包含多个.mbt
文件,这些文件是MoonBit语言的源代码文件。不过,无论包中有多少个.mbt
文件,它们都共享一个公共的moon.pkg
文件。moon.pkg
文件:包描述符文件。它定义了包的属性,例如包的名称和导入的包。moon.mod
用于将目录标识为MoonBit模块。它包含模块的名称:./moon.modmodule "hello"
检查项目
使用Visual Studio Code打开项目。在安装了MoonBit插件之后,在终端中使用moon check --watch
命令自动检查项目。
执行moon check --watch
之后,VS Code应该如下所示。
使用包
我们的hello
模块包含两个包:lib
和main
。
lib
包含一个hello.mbt
文件:
pub func hello() -> String {
"Hello, world!\n"
}
main
包含一个main.mbt
文件:
func init {
@lib.hello().print()
}
要执行您的程序,请指定路径到main
包:
$ moon run ./main
Hello, world!
包导入
在MoonBit的构建系统中,模块的名称用于引用其内部包。
要在main/main.mbt
中导入lib
包,需要在main/moon.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
包:
import "hello/utils"
pub func hello() -> String {
let currentTime = utils.getTime()
"Hello, world! The current time is " + currentTime + "\n"
}
然后,在utils
包的.mbt
文件中实现getTime
函数:
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的旅程中取得成功!