`deno init`,启动一个新项目
命令行用法
deno init [OPTIONS] [DIRECTORY OR PACKAGE]...
使用脚本、测试和配置文件搭建一个基本的 Deno 项目
选项 跳转到标题
--lib
跳转到标题
生成一个示例库项目。
--npm
跳转到标题
生成一个 npm create-* 项目。
--serve
跳转到标题
为 deno serve
生成一个示例项目。
示例 跳转到标题
$ 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 包 跳转到标题
通过运行 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 服务器 跳转到标题
运行 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"
}
}
现在,你可以启动你的 Web 服务器,它会监视更改,通过运行 deno task dev
。
$ deno task dev
Task dev deno serve --watch -R main.ts
Watcher Process started.
deno serve: Listening on http://0.0.0.0:8000/
生成库项目 跳转到标题
你可以附加一个 --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"
}
}