Reputation: 31
i use template literal in javaScript
let innerHTML = `<div><span>like this</span></div>`;
is it possible to automatically indent or prettier like jsx in intellij?
when i press [ ctrl + alt + l ] change nothing
i want to make this format automatically
let innerHTML = `<div>
<span>
like this
</span>
</div>`;
is it possible?
Upvotes: 3
Views: 5557
Reputation: 242
You can use Tagged templates;
const innerHtml = html`
<img src=${Icon} id="content-logo" />
`;
If you faced this kind of error: ReferenceError: html is not defined
. You can define html
function by your own;
const html = (strings, ...values) =>
String.raw({ raw: strings }, ...values);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#raw_strings
Upvotes: 1
Reputation: 1248
You can simply add a comment before your template string and Prettier will pick it up:
function vanillaComponent() {
return /* HTML */ `
<div>
<h1>Hello</h1>
</div>
`
}
At the moment the comment has to be uppercase or it doesn't work. Tested using VSCode.
Upvotes: 9
Reputation: 31849
If you're using Prettier, you should use a template literal tag to mark it as HTML, otherwise it doesn't know that that string contains HTML.
Prettier calls this embedded language, you can see below that this also enables various syntax highlighters.
This line:
let innerHTML = html`
<div><span> This is a very long line that should be wrapped 123456789 123456789 123456789 </span></div>
`;
Is wrapped as
let innerHTML = html`
<div>
<span>
This is a very long line that should be wrapped 123456789 123456789
123456789
</span>
</div>
`;
You can get this html
function and others from code-tag
:
npm install code-tag
import { html } from 'code-tag';
html`<div>this is page "${document.title}"`
Upvotes: 6
Reputation: 476
If you are using Visual Studio Code you can use this extension: https://marketplace.visualstudio.com/items?itemName=Tobermory.es6-string-html
(I'm sure there is equivalent extension for others IDE)
Upvotes: 1