多行字符串保持可读性



我知道我可以在JS中使用带有反引号的多行字符串,但是,它也拾取空格作为字符串的一部分。这是预期的行为,但我希望它们缩进以获得更好的可读性。是否可以使用反引号,或者我需要使用串联。

提前谢谢。

const testFunc = () => {
console.log(`This is line One,
this is line Two`); //Outputs line by line.
}
testFunc();
const testFuncTwo = () => {
console.log(`This is line One,
this is line two`); //Cleaner, but the second line starts after the indentation. 
}
testFuncTwo();

您可以使用 ES6 标记从多行字符串中删除缩进。

在这个例子中,我使用的是 dedent npm 包,但还有其他几个包也这样做:

// Commented-out for browser compatibility; un-comment for node.js
// const dedent = require('dedent')
function usageExample() {
const first = dedent`A string that gets so long you need to break it over
multiple lines. Luckily dedent is here to keep it
readable without lots of spaces ending up in the string
itself.`;

const second = dedent`
Leading and trailing lines will be trimmed, so you can write something like
this and have it work as you expect:

* how convenient it is
* that I can use an indented list
- and still have it do the right thing

That's all.
`;

const third = dedent(`
Wait! I lied. Dedent can also be used as a function.
`);

return first + "nn" + second + "nn" + third;
}
console.log(usageExample())
<script src="https://unpkg.com/dedent@0.7.0/dist/dedent.js"></script>

不幸的是,没有办法自动处理它。 但是,也可以选择字符串连接技巧:

const src = [
'// updated at build time by the CI',
`export const ${key} = '${value}';`
]
.join('n');

const src = [
'// updated at build time by the CI',
`export const ${key} = '${value}';`
]
.map(line => line + 'n')
.join('');

你所要求的是不可能的。省略缩进会造成视觉混乱。因此,如果您想以更好的格式方式拆分它,则必须使用串联。但是,一旦中间有行,无论如何,在这两种情况下,编辑单行都会对所有后续行产生影响,编辑单行就会变得很痛苦。此外,这两种变体都使文本的可搜索性降低。这就是为什么 Airbnb JavaScript 风格指南完全抛弃了两者。

相关规则摘录:

// bad
const errorMessage = 'This is a super long error that was thrown because 
of Batman. When you stop to think about how Batman had anything to do 
with this, you would get nowhere 
fast.';
// bad
const errorMessage = 'This is a super long error that was thrown because ' +
'of Batman. When you stop to think about how Batman had anything to do ' +
'with this, you would get nowhere fast.';
// good
const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';

理想情况下,您希望 IDE 或编辑器为您处理显示大字符串。

对于换行符,只需在字符串中需要的地方使用n即可。

根据您的具体问题,您还可以使用数组来解决这个问题,例如每个元素代表一条线,并用nsjoin它们。在格式化时,与上述相同的规则适用。

最新更新