justjavac / justjavac/justjavac.github.com

一个关于模板字符串的使用技巧,以及 String.raw() 函数

Open
#10 2 comments 0 reactions 1 assignee Claimed by @justjavac View on GitHub
blog
Dominant language
HTML
Stars
607
Forks
182
PR merge metrics
No merged PRs in 30d

Description

在做前端开发的时候,我们经常会需要在 JavaScript 文件中书写 html 或者 css。在这种场景下,使用模板字符串是个很好的方式,这样就不需要进行复杂而丑陋的字符串拼接了。

SomeHats 在 [twitter](https://twitter.com/SomeHats/status/960138211350728704) 上给出了一个使用模板字符串的技巧:

![](https://user-images.githubusercontent.com/359395/35918448-d9aa15ce-0c4c-11e8-8d7f-5b6bfc513ec7.png)

![](https://user-images.githubusercontent.com/359395/35918461-e40fed2c-0c4c-11e8-9cf0-c5e6e99a9adf.png)

仔细看两张图,应该观察到不同了吧。

直接使用模板字符串赋值 `const trired = `...`;` 时,编辑器没有对模板字符串进行语法高亮。而使用
tagged template string (例 `const wired = html`...`;`) 时,编辑器对对模板字符串进行了语法高亮显示。

我试了一下我的 vscode 1.19.3,对于 css 可以正常语法高亮,对于 html 没有语法高亮。如果需要特殊的插件,请在评论区留言。

还有一个好处就是像 Prettier 这样的格式化工具可以对其进行格式化处理。

我的测试结果是,对于 `css`...`` 可以正常处理,而 `html`...`` 作为了普通模板字符串。

我们还可以封装一下 `String.raw`,把它放在单独的文件夹中:

![](https://user-images.githubusercontent.com/359395/35918945-763c4668-0c4e-11e8-8557-ffa98871d0d4.png)

随后作者突然意识到自己的一个错误,这两种写法并不是等价的:

![](https://user-images.githubusercontent.com/359395/35919013-ab0c9a46-0c4e-11e8-86eb-c81a5a6b0ca0.png)

`String.raw` 是用来获取一个模板字符串的**原始字面量**值的。MDN 的官方例子:

```javascript
String.raw `Hi\n!`;
// "Hi\\n!",这里得到的不是 Hi 后面跟个换行符,而是跟着 \ 和 n 两个字符

String.raw `Hi\u000A!`;
// "Hi\\u000A!",同上,这里得到的会是 \、u、0、0、0、A 6个字符,
// 任何类型的转义形式都会失效,保留原样输出,不信你试试.length

let name = "Bob";
String.raw `Hi\n${name}!`;
// "Hi\\nBob!",内插表达式还可以正常运行

String.raw({raw: "test"}, 0, 1, 2);
// "t0e1s2t",我认为你通常不需要把它当成普通函数来调用
```

我们需要修改一下之前的代码:

![](https://user-images.githubusercontent.com/359395/35919088-f1ea9792-0c4e-11e8-8ae1-b84d7339395a.png)

细看下来,这种 tagged template string 的写法很像 Github-flavoured Markdown。

It's cool.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.