deno init
,启动一个新项目
命令行用法
deno init [OPTIONS] [DIRECTORY OR PACKAGE]...
生成一个包含脚本、测试和配置文件的基本 Deno 项目
选项 Jump to heading
--lib
Jump to heading
生成一个示例库项目。
--npm
Jump to heading
生成一个 npm create-* 项目。
--serve
Jump to heading
为 deno serve
生成一个示例项目。
示例 Jump to heading
$ deno init
✅ Project initialized
Run these commands to get started
// Run the program
deno run main.ts
// Run the program and watch for file changes
deno task dev
// Run the tests
deno test
$ deno run main.ts
Add 2 + 3 = 5
$ deno test
Check file:///dev/main_test.ts
running 1 test from main_test.ts
addTest ... ok (6ms)
ok | 1 passed | 0 failed (29ms)
init
子命令将创建两个文件(main.ts
和 main_test.ts
)。这些文件提供了一个如何编写 Deno 程序以及如何为其编写测试的基本示例。main.ts
文件导出一个 add
函数,用于将两个数字相加,而 main_test.ts
文件包含此函数的测试。
您还可以为 deno init
指定一个参数,以在特定目录中初始化项目
$ deno init my_deno_project
✅ Project initialized
Run these commands to get started
cd my_deno_project
// Run the program
deno run main.ts
// Run the program and watch for file changes
deno task dev
// Run the tests
deno test
初始化 JSR 包 Jump to heading
通过运行 deno init --lib
,Deno 将引导一个准备好发布到 JSR 的项目。
$ deno init --lib
✅ Project initialized
Run these commands to get started
# Run the tests
deno test
# Run the tests and watch for file changes
deno task dev
# Publish to JSR (dry run)
deno publish --dry-run
在 deno.json
中,您会看到 name
、exports
和 version
的条目已预填充。
{
"name": "my-lib",
"version": "0.1.0",
"exports": "./mod.ts",
"tasks": {
"dev": "deno test --watch mod.ts"
},
"imports": {
"@std/assert": "jsr:@std/assert@1"
}
}
初始化 Web 服务器 Jump to heading
运行 deno init --serve
会引导一个与 deno serve
协同工作的 Web 服务器。
$ deno init --serve
✅ Project initialized
Run these commands to get started
# Run the server
deno serve -R main.ts
# Run the server and watch for file changes
deno task dev
# Run the tests
deno -R test
您的 deno.json
文件将如下所示
{
"tasks": {
"dev": "deno serve --watch -R main.ts"
},
"imports": {
"@std/assert": "jsr:@std/assert@1",
"@std/http": "jsr:@std/http@1"
}
}
现在,您可以通过运行 deno task dev
来启动您的 Web 服务器,该服务器会监视更改。
$ deno task dev
Task dev deno serve --watch -R main.ts
Watcher Process started.
deno serve: Listening on http://0.0.0.0:8000/
生成库项目 Jump to heading
您可以附加 --lib
标志,为您的 deno.json
添加额外参数,例如 "name"、"version" 和 "exports" 字段。
$ deno init my_deno_project --lib
✅ Project initialized
生成的 `deno.json` 将如下所示
{
"name": "my_deno_project",
"version": "0.1.0",
"exports": "./mod.ts",
"tasks": {
"dev": "deno test --watch mod.ts"
},
"license": "MIT",
"imports": {
"@std/assert": "jsr:@std/assert@1"
}
}