← 中文资源

简体中文版本

dedent 去除公共前导缩进

dedent 找出所有非空行中最小的前导缩进并逐行剥掉:无论调用处嵌套多深,多行模板文本都能输出为顶格、可读、可直接打印的字符串。

阅读英文原文

实现说明

全部逻辑都在函数 dedent、renderBanner中。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 dedent、renderBanner。

主签名形如 function dedent(strings, ...values)

核心语句

return lines.map((line) => line.slice(pad)).join('\n').trimEnd();
.map((line) => line.match(/^[ \t]*/)[0].length);
if (i < values.length) text += values[i];

代码示例

// Multi-line template literals keep the source indentation of the
// call site. dedent splices values back in, finds the smallest
// leading indent across non-blank lines, and strips it everywhere.
function dedent(strings, ...values) {
  let text = '';
  strings.forEach((chunk, i) => {
    text += chunk;
    if (i < values.length) text += values[i];
  });

  const lines = text.replace(/^\n/, '').split('\n');
  const indents = lines
    .filter((line) => line.trim().length > 0)
    .map((line) => line.match(/^[ \t]*/)[0].length);
  const pad = Math.min(...indents);

  return lines.map((line) => line.slice(pad)).join('\n').trimEnd();
}

function renderBanner(name) {
  return dedent`
    *** deploy report ***
    service: ${name}
    status: ready
  `;
}

console.log(renderBanner('billing'));