# css-tree 中文文档

规范地址：https://npmcn.com/package/css-tree/

版本：3\.2\.1
npm 元数据更新时间：2026-03-05T14:12:36.989Z
中文译文更新时间：2026-11-05T02:22:22.763Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/css-tree
原文对照：https://npmcn.com/package/css-tree/?lang=original
项目主页：https://github.com/csstree/csstree#readme
源码仓库：https://github.com/csstree/csstree

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.4 MB，278 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：未声明
- Node.js 要求：^10 \|\| ^12\.20\.0 \|\| ^14\.13\.0 \|\| \>=15\.0\.0
- 运行依赖：2 个
- 首次发布：2016-09-12T19:34:13.785Z
- 最新版本发布：2026-03-05T14:12:36.884Z
- 近 30 天下载量：522254663（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：61（近 12 个月 2 个）

## 中文简介

CSS工具集：基于规范和浏览器实现的快速详细解析器（CSS→AST）、遍历器（AST遍历）、生成器（AST→CSS）和词法分析器（验证和匹配）

## 安装

```sh
npm install css-tree
```

也可以使用：`pnpm add css-tree`、`yarn add css-tree`、`bun add css-tree`

## README

![CSSTree logo](https://npmcn.com/package/css-tree/assets/csstree-logo-rounded.svg)

# CSSTree

[![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Build Status](https://github.com/csstree/csstree/actions/workflows/build.yml/badge.svg)](https://github.com/csstree/csstree/actions/workflows/build.yml) [![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master) [![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree)

CSSTree是一个CSS工具集： [快](https://github.com/postcss/benchmark) 基于规范和浏览器实现的详细解析器（CSS→AST）、遍历器（AST遍历）、生成器（AST→CSS）和词法分析器（验证和匹配）。主要目标是高效且符合W3C规范，重点是CSS分析和源到源转换任务。

## 特性

-   **具有可调整的详细级别的详细解析**
    
    默认情况下，CSSTree尽可能详细地解析CSS，即每个逻辑部分都用自己的AST节点表示(参见 [AST格式](https://npmcn.com/package/css-tree/docs/ast.md) 对于所有可能的节点类型)。解析细节级别可以通过以下方式更改 [解析器选项](https://npmcn.com/package/css-tree/docs/parsing.md#parsesource-options)例如，您可以禁用对组件部件的选择器或声明值的解析。
    
-   **能容忍错误的**
    
    解析器的行为如下 [规范说](https://www.w3.org/TR/css-syntax-3/#error-handling)：“当CSS中出现错误时，解析器会尝试优雅地恢复，在返回正常解析之前只丢弃最少量的内容”。解析器与规范的唯一不同之处在于，它不会丢弃不良内容，而是将其包装在特殊的节点类型中(`Raw`)，以便稍后处理。
    
-   **快速高效**
    
    CSSTree的创建重点是性能和有效的内存消耗。因此,它的 [最快的CSS解析器之一](https://github.com/postcss/benchmark) 目前为止。
    
-   **语法验证**
    
    内置词法分析器可以根据W3C定义的语法测试CSS。CSSTree使用 [mdn /数据](https://github.com/mdn/data/) 作为lexer字典的基础，并使用特定于供应商的遗留语法对其进行扩展。Lexer目前只能检查声明值和at-rules，但这个特性将来会扩展到CSS的其他部分。
    

## 使用csstreet的项目

-   [苗条的](https://github.com/sveltejs/svelte) -控制论增强的web应用程序
-   [SVGO](https://github.com/svg/svgo) -优化SVG文件的Node.js工具
-   [CSSO](https://github.com/css/csso) - CSS微缩与结构优化
-   [NativeScript](https://github.com/NativeScript/NativeScript) NativeScript允许你直接从JavaScript访问本地api
-   [react-native-svg](https://github.com/react-native-svg/react-native-svg) -用于React Native， React Native Web和纯React Web项目的SVG库
-   [《阁楼》](https://github.com/pocketjoso/penthouse) —关键路径CSS生成器
-   [位](https://github.com/teambit/bit) - Bit是组件协作的平台
-   和更多的……

## 文档

-   [AST格式](https://npmcn.com/package/css-tree/docs/ast.md)
-   [解析CSS→AST](https://npmcn.com/package/css-tree/docs/parsing.md)
    -   [解析(源\[选项\])](https://npmcn.com/package/css-tree/docs/parsing.md#parsesource-options)
-   [序列化AST→CSS](https://npmcn.com/package/css-tree/docs/generate.md)
    -   [生成(ast\[选项\])](https://npmcn.com/package/css-tree/docs/generate.md#generateast-options)
-   [AST遍历](https://npmcn.com/package/css-tree/docs/traversal.md)
    -   [步行(ast、期权)](https://npmcn.com/package/css-tree/docs/traversal.md#walkast-options)
    -   [找到(ast, fn)](https://npmcn.com/package/css-tree/docs/traversal.md#findast-fn)
    -   [fn findLast (ast)](https://npmcn.com/package/css-tree/docs/traversal.md#findlastast-fn)
    -   [fn findAll (ast)](https://npmcn.com/package/css-tree/docs/traversal.md#findallast-fn)
-   [Util功能](https://npmcn.com/package/css-tree/docs/utils.md)
    -   值编码与解码
        -   [属性(名称)](https://npmcn.com/package/css-tree/docs/utils.md#propertyname)
        -   [关键字(名字)](https://npmcn.com/package/css-tree/docs/utils.md#keywordname)
        -   [鉴别](https://npmcn.com/package/css-tree/docs/utils.md#ident)
        -   [字符串](https://npmcn.com/package/css-tree/docs/utils.md#string)
        -   [url](https://npmcn.com/package/css-tree/docs/utils.md#url)
    -   [列表类](https://npmcn.com/package/css-tree/docs/list.md)
    -   AST转换
        -   [克隆(ast)](https://npmcn.com/package/css-tree/docs/utils.md#cloneast)
        -   [fromPlainObject(对象)](https://npmcn.com/package/css-tree/docs/utils.md#fromplainobjectobject)
        -   [toPlainObject (ast)](https://npmcn.com/package/css-tree/docs/utils.md#toplainobjectast)
-   [值定义语法](https://npmcn.com/package/css-tree/docs/definition-syntax.md)
    -   [解析(源)](https://npmcn.com/package/css-tree/docs/definition-syntax.md#parsesource)
    -   [遍历（节点、选项、上下文）](https://npmcn.com/package/css-tree/docs/definition-syntax.md#walknode-options-context)
    -   [生成(节点,选项)](https://npmcn.com/package/css-tree/docs/definition-syntax.md#generatenode-options)
    -   [AST格式](https://npmcn.com/package/css-tree/docs/definition-syntax.md#ast-format)

## 工具

-   [AST探险家](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) -探索CSSTree AST格式与零设置
-   [CSS语法参考](https://csstree.github.io/docs/syntax.html)
-   [CSS语法验证器](https://csstree.github.io/docs/validator.html)

## 相关项目

-   [csstree-validator](https://github.com/csstree/validator) - NPM包来验证CSS
-   [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) -插件的样式来验证CSS
-   [繁重的插件](https://github.com/sergejmueller/grunt-csstree-validator)
-   [吞咽插件](https://github.com/csstree/gulp-csstree)
-   [崇高的插件](https://github.com/csstree/SublimeLinter-contrib-csstree)
-   [VS Code插件](https://github.com/csstree/vscode-plugin)
-   [原子插件](https://github.com/csstree/atom-plugin)

## 用法

使用npm安装：

```
npm install css-tree
```

基本用法:

```js
import * as csstree from 'css-tree';

// parse CSS to AST
const ast = csstree.parse('.example { world: "!" }');

// traverse AST and modify it
csstree.walk(ast, (node) => {
    if (node.type === 'ClassSelector' && node.name === 'example') {
        node.name = 'hello';
    }
});

// generate CSS from AST
console.log(csstree.generate(ast));
// .hello{world:"!"}
```

语法匹配:

```js
// parse CSS to AST as a declaration value
const ast = csstree.parse('red 1px solid', { context: 'value' });

// match to syntax of `border` property
const matchResult = csstree.lexer.matchProperty('border', ast);

// check first value node is a <color>
console.log(matchResult.isType(ast.children.first, 'color'));
// true

// get a type list matched to a node
console.log(matchResult.getTrace(ast.children.first));
// [ { type: 'Property', name: 'border' },
//   { type: 'Type', name: 'color' },
//   { type: 'Type', name: 'named-color' },
//   { type: 'Keyword', name: 'red' } ]
```

### 出口

是否有可能只导入库中所需的部分，如解析器或walker。这对于加载时间或包大小优化可能很有用。

```js
import * as tokenizer from 'css-tree/tokenizer';
import * as parser from 'css-tree/parser';
import * as walker from 'css-tree/walker';
import * as lexer from 'css-tree/lexer';
import * as definitionSyntax from 'css-tree/definition-syntax';
import * as data from 'css-tree/definition-syntax-data';
import * as dataPatch from 'css-tree/definition-syntax-data-patch';
import * as utils from 'css-tree/utils';
```

### 在浏览器中使用

bundle可以在浏览器中使用：

-   `dist/csstree.js` 与…一起生活 `csstree` 随着全球

```html
<script src="node_modules/css-tree/dist/csstree.js"></script>
<script>
  csstree.parse('.example { color: green }');
</script>
```

-   `dist/csstree.esm.js` -缩小的ES模块

```html
<script type="module">
  import { parse } from 'node_modules/css-tree/dist/csstree.esm.js'
  parse('.example { color: green }');
</script>
```

CDN服务之一 `unpkg` 或 `jsDelivr` 可以使用。默认情况下（对于短路径），ESM版本是公开的。对于IIFE版本，应该指定bundle的完整路径：

```html
<!-- ESM -->
<script type="module">
  import * as csstree from 'https://cdn.jsdelivr.net/npm/css-tree';
  import * as csstree from 'https://unpkg.com/css-tree';
</script>

<!-- IIFE with an export to global -->
<script src="https://cdn.jsdelivr.net/npm/css-tree/dist/csstree.js"></script>
<script src="https://unpkg.com/css-tree/dist/csstree.js"></script>
```

## 顶层API

![API map](https://cdn.rawgit.com/csstree/csstree/aaf327e/docs/api-map.svg)

## 许可证

麻省理工学院

## 常见问题

### css-tree 是什么？

CSS工具集：基于规范和浏览器实现的快速详细解析器（CSS→AST）、遍历器（AST遍历）、生成器（AST→CSS）和词法分析器（验证和匹配）

### 如何安装 css-tree？

在项目目录运行 npm install css-tree，或使用 pnpm add / yarn add / bun add。

### css-tree 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/css-tree 是否存在。

### css-tree 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### css-tree 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^10 \|\| ^12\.20\.0 \|\| ^14\.13\.0 \|\| \>=15\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### css-tree 可以商用吗？

css-tree 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### css-tree 的下载量有多少？

根据 npm 官方下载统计，css-tree 在 2026/10/05 – 2026/11/03 这 30 天内被下载 522,254,663 次，日均约 17,408,489 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### css-tree 还在维护吗？

最新版本 3\.2\.1 发布于 2026/03/05（8 个月前）；至今共发布 61 个版本，其中过去 12 个月发布了 2 个；首次发布于 2016/09/13。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

