Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

项目中 javascript 代码模板可以通过 tagged templates 来美化代码格式 #7924

Open
SyMind opened this issue Oct 26, 2020 · 0 comments
Labels
E-medium Helper Wanted - Medium enhancement New feature or request

Comments

@SyMind
Copy link
Member

SyMind commented Oct 26, 2020

这个特性解决了什么问题?

当前的代码中为了避免 template strings 产生多余的缩进,导致代码格式很奇怪,可以使用 tagged templates 来优化代码格式。

这个 API 长什么样?

// 为了避免多余的缩进,将 template strings 置与行首
function getCodeSnippet() {
    return `
var world = 'world';
console.log('hello, '   world);
`;
}

// 不必将 template strings 置与行首
function getCodeSnippet() {
    return unIndex`
        var world = 'world';
        console.log('hello, '   world);
    `;
}

// tagged templates 移除多余的缩进
function unIndent(strings, ...values) {
    const text = strings
        .map((s, i) => (i === 0 ? s : values[i - 1]   s))
        .join("");
    const lines = text.replace(/^\n/u, "").replace(/\n\s*$/u, "").split("\n");
    const lineIndents = lines.filter(line => line.trim()).map(line => line.match(/ */u)[0].length);
    const minLineIndent = Math.min(...lineIndents);

    return lines.map(line => line.slice(minLineIndent)).join("\n");
}
@taro-bot2 taro-bot2 bot added the enhancement New feature or request label Oct 26, 2020
@SyMind SyMind changed the title 项目中的 javascript 代码模板可以使用 tagged templates 来美化 项目中 javascript 代码模板可以通过 tagged templates 来美化代码格式 Oct 26, 2020
@ZakaryCode ZakaryCode added the E-medium Helper Wanted - Medium label Feb 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
E-medium Helper Wanted - Medium enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants