observable-notebook-kit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Observable Notebook Kit

Observable Notebook Kit

Observable Notebook Kit is an open-source CLI and Vite plugin for building static sites from Observable Notebooks.
Observable Notebook Kit 是一款开源的CLI和Vite插件,用于从Observable Notebooks构建静态站点。

File Format

文件格式

Notebooks are
.html
files with this structure:
html
<!doctype html>
<notebook theme="air">
  <title>My Notebook</title>
  <script type="text/markdown">
    # Hello
  </script>
  <script type="module" pinned>
    1 + 2
  </script>
</notebook>
笔记本是具有以下结构的
.html
文件:
html
<!doctype html>
<notebook theme="air">
  <title>My Notebook</title>
  <script type="text/markdown">
    # Hello
  </script>
  <script type="module" pinned>
    1 + 2
  </script>
</notebook>

<notebook>
Attributes

<notebook>
标签属性

  • theme
    - colorway:
    air
    (default),
    coffee
    ,
    cotton
    ,
    deep-space
    ,
    glacier
    ,
    ink
    ,
    midnight
    ,
    near-midnight
    ,
    ocean-floor
    ,
    parchment
    ,
    slate
    ,
    stark
    ,
    sun-faded
  • readonly
    - disallow editing
  • theme
    - 配色方案:
    air
    (默认)、
    coffee
    cotton
    deep-space
    glacier
    ink
    midnight
    near-midnight
    ocean-floor
    parchment
    slate
    stark
    sun-faded
  • readonly
    - 禁止编辑

<script>
(Cell) Attributes

<script>
(单元格)属性

  • type
    - cell language (required)
  • pinned
    - show source code
  • hidden
    - suppress display
  • output
    - variable name to expose (for non-JS cells)
  • database
    - database name (SQL cells)
  • format
    - output format (data loader cells)
  • id
    - cell identifier
  • type
    - 单元格语言(必填)
  • pinned
    - 显示源代码
  • hidden
    - 隐藏输出
  • output
    - 要暴露的变量名(非JS单元格适用)
  • database
    - 数据库名称(SQL单元格适用)
  • format
    - 输出格式(数据加载器单元格适用)
  • id
    - 单元格标识符

Cell Types (
type
values)

单元格类型(
type
取值)

TypeLanguage
module
JavaScript
text/x-typescript
TypeScript
text/markdown
Markdown
text/html
HTML
application/sql
SQL
application/x-tex
TeX/LaTeX
text/vnd.graphviz
DOT (Graphviz)
application/vnd.node.javascript
Node.js data loader
text/x-python
Python data loader
text/x-r
R data loader
Use 4 spaces indentation inside
<script>
(auto-trimmed). Escape
</script>
as
<\/script>
.
类型语言
module
JavaScript
text/x-typescript
TypeScript
text/markdown
Markdown
text/html
HTML
application/sql
SQL
application/x-tex
TeX/LaTeX
text/vnd.graphviz
DOT (Graphviz)
application/vnd.node.javascript
Node.js 数据加载器
text/x-python
Python 数据加载器
text/x-r
R 数据加载器
<script>
标签内使用4个空格缩进(会自动修剪)。将
</script>
转义为
<\/script>

CLI Commands

CLI命令

Install:
npm add @observablehq/notebook-kit
安装:
npm add @observablehq/notebook-kit

Preview

预览

sh
notebooks preview --root docs
notebooks preview --root docs --template docs/custom.tmpl
sh
notebooks preview --root docs
notebooks preview --root docs --template docs/custom.tmpl

Build

构建

sh
notebooks build --root docs -- docs/*.html
Output goes to
.observable/dist
.
sh
notebooks build --root docs -- docs/*.html
输出文件将生成到
.observable/dist
目录。

Download

下载

Convert Observable notebook URL to local HTML:
sh
notebooks download https://observablehq.com/@d3/bar-chart > bar-chart.html
将Observable笔记本URL转换为本地HTML文件:
sh
notebooks download https://observablehq.com/@d3/bar-chart > bar-chart.html

Query

查询

Run database query manually:
sh
notebooks query --database duckdb 'SELECT 1 + 2'
手动运行数据库查询:
sh
notebooks query --database duckdb 'SELECT 1 + 2'

JavaScript in Notebooks

笔记本中的JavaScript

Expression vs Program Cells

表达式单元格与程序单元格

Expression cell (implicit display):
js
1 + 2
Program cell (explicit display):
js
const foo = 1 + 2;
display(foo);
表达式单元格(自动显示结果):
js
1 + 2
程序单元格(手动控制显示):
js
const foo = 1 + 2;
display(foo);

Key Built-ins

核心内置函数

  • display(value)
    - render value to cell output
  • view(input)
    - display input, return value generator
  • FileAttachment("path")
    - load local files (same/sub directory only)
  • invalidation
    - promise for cleanup on re-run
  • visibility
    - promise when cell visible
  • width
    - current page width
  • now
    - current time
  • display(value)
    - 将值渲染到单元格输出
  • view(input)
    - 显示输入组件,返回值生成器
  • FileAttachment("path")
    - 加载本地文件(仅支持当前目录或子目录)
  • invalidation
    - 重新运行时用于清理的Promise
  • visibility
    - 单元格变为可见时的Promise
  • width
    - 当前页面宽度
  • now
    - 当前时间

Standard Library

标准库

  • Inputs
    - Observable Inputs
  • Plot
    - Observable Plot
  • d3
    - D3.js
  • htl
    ,
    html
    ,
    svg
    - Hypertext Literal
  • tex
    ,
    md
    - tagged template literals
  • Inputs
    - Observable 输入组件库
  • Plot
    - Observable 可视化库
  • d3
    - D3.js
  • htl
    ,
    html
    ,
    svg
    - 超文本字面量工具
  • tex
    ,
    md
    - 标签模板字面量

Imports

导入

js
import lib from "npm:package-name";
import {fn} from "jsr:@scope/package";
js
import lib from "npm:package-name";
import {fn} from "jsr:@scope/package";

Reactivity

响应式特性

Top-level variables trigger re-runs. Promises auto-await; generators yield latest value.
js
const x = view(Inputs.range([0, 100]));
js
x ** 2  // re-runs when x changes
顶级变量变更会触发单元格重新运行。Promise会自动等待;生成器会返回最新值。
js
const x = view(Inputs.range([0, 100]));
js
x ** 2  // 当x变化时自动重新运行

Interpolation

插值

Use
${...}
in Markdown/HTML cells:
md
The answer is ${x * 2}.
在Markdown/HTML单元格中使用
${...}
进行插值:
md
答案是${x * 2}。

Database Connectors

数据库连接器

See references/databases.md for full configuration.
完整配置请查看references/databases.md

Quick Setup

快速设置

SQL cells use
database
attribute. Default is
duckdb
(in-memory).
html
<script type="application/sql" database="duckdb" output="results">
  SELECT * FROM 'data.parquet'
</script>
SQL单元格使用
database
属性指定数据库。默认使用
duckdb
(内存数据库)。
html
<script type="application/sql" database="duckdb" output="results">
  SELECT * FROM 'data.parquet'
</script>

Supported Databases

支持的数据库

  • DuckDB (
    @duckdb/node-api
    )
  • SQLite (Node.js 24+ built-in)
  • Postgres (
    postgres
    )
  • Snowflake (
    snowflake-sdk
    )
  • BigQuery (
    @google-cloud/bigquery
    )
  • Databricks (
    @databricks/sql
    )
Install drivers separately:
npm add @duckdb/node-api
  • DuckDB(需安装
    @duckdb/node-api
  • SQLite(Node.js 24+ 内置支持)
  • Postgres(需安装
    postgres
  • Snowflake(需安装
    snowflake-sdk
  • BigQuery(需安装
    @google-cloud/bigquery
  • Databricks(需安装
    @databricks/sql
需单独安装驱动:
npm add @duckdb/node-api

Query Results

查询结果

  • Auto-cached in
    .observable/cache
  • Re-run via Play button or Shift+Enter in Desktop
  • Delete cache file to refresh in Notebook Kit
  • 自动缓存到
    .observable/cache
    目录
  • 在桌面端可通过播放按钮或Shift+Enter重新运行查询
  • 在Notebook Kit中可删除缓存文件以刷新结果

Dynamic Queries

动态查询

js
const db = DatabaseClient("duckdb");
const data = await db.sql`SELECT * FROM t WHERE x = ${value}`;
js
const db = DatabaseClient("duckdb");
const data = await db.sql`SELECT * FROM t WHERE x = ${value}`;

Data Loaders

数据加载器

Cells that run at build time via interpreter. Output cached in
.observable/cache
.
在构建时通过解释器运行的单元格。输出结果缓存到
.observable/cache
目录。

Formats

输出格式

Text:
text
,
json
,
csv
,
tsv
,
xml
Binary:
arrow
,
parquet
,
blob
,
buffer
Image:
png
,
jpeg
,
gif
,
webp
,
svg
Other:
html
文本格式:
text
json
csv
tsv
xml
二进制格式:
arrow
parquet
blob
buffer
图片格式:
png
jpeg
gif
webp
svg
其他格式:
html

Node.js

Node.js

html
<script type="application/vnd.node.javascript" format="json" output="data">
  process.stdout.write(JSON.stringify({hello: "world"}));
</script>
Requires Node.js 22.12+. Sandboxed with read-only access to notebook directory.
html
<script type="application/vnd.node.javascript" format="json" output="data">
  process.stdout.write(JSON.stringify({hello: "world"}));
</script>
要求Node.js 22.12+版本。处于沙箱环境,仅对笔记本目录有只读权限。

Python

Python

html
<script type="text/x-python" format="text" output="result">
  print("hello", end="")
</script>
Requires Python 3.12+. Uses
.venv
if present.
html
<script type="text/x-python" format="text" output="result">
  print("hello", end="")
</script>
要求Python 3.12+版本。若存在
.venv
则使用该虚拟环境。

R

R

html
<script type="text/x-r" format="json" output="data">
  cat(jsonlite::toJSON(list(x = 1:3)))
</script>
html
<script type="text/x-r" format="json" output="data">
  cat(jsonlite::toJSON(list(x = 1:3)))
</script>

Page Templates

页面模板

Custom templates wrap built notebooks:
html
<!doctype html>
<html>
  <head>
    <style>@import url("observable:styles/index.css");</style>
  </head>
  <body>
    <main></main>  <!-- notebook renders here -->
  </body>
</html>
Use
--template path.tmpl
with CLI.
自定义模板可包裹构建后的笔记本:
html
<!doctype html>
<html>
  <head>
    <style>@import url("observable:styles/index.css");</style>
  </head>
  <body>
    <main></main>  <!-- 笔记本将渲染到此处 -->
  </body>
</html>
在CLI中使用
--template path.tmpl
参数指定模板。

Project Setup

项目设置

Typical
package.json
:
json
{
  "dependencies": {
    "@observablehq/notebook-kit": "^"
  },
  "scripts": {
    "docs:preview": "notebooks preview --root docs",
    "docs:build": "notebooks build --root docs -- docs/*.html"
  }
}
典型的
package.json
配置:
json
{
  "dependencies": {
    "@observablehq/notebook-kit": "^"
  },
  "scripts": {
    "docs:preview": "notebooks preview --root docs",
    "docs:build": "notebooks build --root docs -- docs/*.html"
  }
}

Configuration Files

配置文件

  • .observable/databases.json
    - database configs (keep out of git)
  • .observable/cache/
    - query/data loader results
  • .observable/dist/
    - built site
Recommended
.gitignore
:
.observable
  • .observable/databases.json
    - 数据库配置文件(请勿提交到git)
  • .observable/cache/
    - 查询/数据加载器结果缓存目录
  • .observable/dist/
    - 构建后的站点目录
推荐的
.gitignore
配置:
.observable