UNPKG

1.88 kBMarkdownView Raw
1# @lwc/template-compiler
2
3Compile LWC HTML template for consumption at runtime.
4
5## Installation
6
7```sh
8yarn add --dev @lwc/template-compiler
9```
10
11## Usage
12
13```js
14import compile from '@lwc/template-compiler';
15
16const { code, warnings } = compile(`
17 <template>
18 <h1>Hello World!</h1>
19 </template>
20`);
21
22for (let warning of warnings) {
23 console.log(warning.message);
24}
25
26console.log(code);
27```
28
29## APIs
30
31### `compile`
32
33Compile a LWC template to javascript source code consumable by the engine.
34
35```js
36import compile from '@lwc/template-compiler';
37const { code, warnings } = compile(`<template><h1>Hello World!</h1></template>`);
38```
39
40**Parameters:**
41
42- `source` (string, required) - the HTML template source to compile.
43
44**Return:**
45The method returns an object with the following fields:
46
47- `code` (string) - the compiled template.
48- `warnings` (array) - the list of warnings produced when compiling the template. Each warning has the following fields:
49 - message (string) - the warning message.
50 - level (string) - the severity of the warning: `info`, `warning`, `error`.
51 - start (number) - the start index in the source code producing the warning.
52 - length (number) - the character length in the source code producing the warning.
53
54### `compileToFunction`
55
56Compile a LWC template to a javascript function. This method is mainly used for testing purposes.
57
58```js
59import { LightningElement } from 'lwc';
60import { compileToFunction } from '@lwc/template-compiler';
61
62const html = compileToFunction(`<template><h1>Hello World!</h1></template>`);
63
64class Component extends LightningElement {
65 render() {
66 return html;
67 }
68}
69```
70
71**Parameters:**
72
73- `source` (string, required) - the HTML template source to compile.
74
75**Return:**
76The method returns an evaluated function that can be used directly in a component `render` method.