deno.com
本頁面內容

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.tsmain_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 內部,您會看到 nameexportsversion 的條目已預先填寫。

{
  "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"
  }
}

您找到需要的資訊了嗎?

隱私權政策