@gwhitney/detect-indent

中文文档
7.0.2发布于 2025/12/09MITTypeScriptCommonJS零依赖近 30 天下载 380.9万

检测代码缩进( commonjs fork)

中文使用文档
文档目录6 节
  1. 使用大小写
  2. 安装
  3. 使用量
  4. API 密码
  5. 算法
  6. 相关

检测缩进

检测代码缩进( commonjs fork)

注: 这是一个叉子 辛德瑞索胡斯/ 检测-缩进 仅修改 恢复提供共同JS出口。 创建它只是为了提供 用于检测缩进的升级路径 pnpm 节点包管理器 . 打算与上游保持同步 detect-indent 财务报告和审定财务报表 使用相同的版本编号。 这个叉子的创造者不赞成 也不批评维护者/ 作者 pnpm 财务报告和审定财务报表 detect-indent 这导致有必要 叉来.

传入任意一种文字的字符串并获得缩进.

使用大小写

  • 修改文件时坚持缩进 .
  • 有与现有缩进相匹配的新内容 .
  • 在编辑器中设置正确的缩进 .

安装

npm install detect-indent

使用量

在此修改 JSON 文件, 同时坚持缩进 :

const fs = require('node:fs');
const detectIndent = require('detect-indent');

/*
{
    "ilove": "pizza"
}
*/
const file = fs.readFileSync('foo.json', 'utf8');

// Tries to detect the indentation and falls back to a default if it can't
const indent = detectIndent(file).indent || '    ';

const json = JSON.parse(file);

json.ilove = 'unicorns';

fs.writeFileSync('foo.json', JSON.stringify(json, undefined, indent));
/*
{
    "ilove": "unicorns"
}
*/

API 密码

接受字符串并返回带有缩进数据的对象 :

  • type -=YTET -伊甸园字幕组=- 翻译: 缩入之类. 没错 undefined 如果没有检测到缩进.
  • amount - 缩进量。 譬如说, 2。 。 。 .
  • indent - 实际缩入.

算法

目前的算法寻找两个相接而来的非空行之间最常见的区别. 单空缩进和变化默认被忽略,以防止常见的假正态对齐.

在下个例子中,即使4-空格缩进出现3次而2-空格只出现2次,也检测出2-空格缩进,因为2个空格有4个缩进变化而4个空格只有2个变化:

html {
  box-sizing: border-box;
}

body {
  background: gray;
}

p {
    line-height: 1.3em;
    margin-top: 1em;
    text-indent: 2em;
}

来源.

此外,如果使用数相同,有多个缩进差异,则选择多行缩进.

在以下例子中,缩进被检测出为4-空格:

body {
  background: gray;
}

p {
    line-height: 1.3em;
    margin-top: 1em;
    text-indent: 2em;
}

版本与发布记录

@gwhitney/detect-indent 共发布 2 个版本,首次发布于 2022/11/22;过去 12 个月发布了 1 个版本。

版本发布日期距今
7.0.2latest2025/12/0911 个月前
7.0.12022/11/223 年前

关于 @gwhitney/detect-indent 的常见问题

@gwhitney/detect-indent 是什么?

检测代码缩进( commonjs fork)

如何安装 @gwhitney/detect-indent?

在项目目录运行 npm install @gwhitney/detect-indent,或使用 pnpm add / yarn add / bun add。

@gwhitney/detect-indent 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gwhitney/detect-indent 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gwhitney/detect-indent 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=12.20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gwhitney/detect-indent 可以商用吗?

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

@gwhitney/detect-indent 的下载量有多少?

根据 npm 官方下载统计,@gwhitney/detect-indent 在 2026/10/17 – 2026/11/15 这 30 天内被下载 3,809,470 次,日均约 126,982 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gwhitney/detect-indent 还在维护吗?

最新版本 7.0.2 发布于 2025/12/09(11 个月前);至今共发布 2 个版本,其中过去 12 个月发布了 1 个;首次发布于 2022/11/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。