1 | # @lwc/template-compiler
|
2 |
|
3 | Compile LWC HTML template for consumption at runtime.
|
4 |
|
5 | ## Installation
|
6 |
|
7 | ```sh
|
8 | yarn add --dev @lwc/template-compiler
|
9 | ```
|
10 |
|
11 | ## Usage
|
12 |
|
13 | ```js
|
14 | import compile from '@lwc/template-compiler';
|
15 |
|
16 | const { code, warnings } = compile(`
|
17 | <template>
|
18 | <h1>Hello World!</h1>
|
19 | </template>
|
20 | `);
|
21 |
|
22 | for (let warning of warnings) {
|
23 | console.log(warning.message);
|
24 | }
|
25 |
|
26 | console.log(code);
|
27 | ```
|
28 |
|
29 | ## APIs
|
30 |
|
31 | ### `compile`
|
32 |
|
33 | Compile a LWC template to javascript source code consumable by the engine.
|
34 |
|
35 | ```js
|
36 | import compile from '@lwc/template-compiler';
|
37 | const { 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:**
|
45 | The 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 |
|
56 | Compile a LWC template to a javascript function. This method is mainly used for testing purposes.
|
57 |
|
58 | ```js
|
59 | import { LightningElement } from 'lwc';
|
60 | import { compileToFunction } from '@lwc/template-compiler';
|
61 |
|
62 | const html = compileToFunction(`<template><h1>Hello World!</h1></template>`);
|
63 |
|
64 | class 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:**
|
76 | The method returns an evaluated function that can be used directly in a component `render` method.
|