实现说明
全部逻辑都在函数 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'));