1 | # babel-template
|
2 |
|
3 | > Generate an AST from a string template.
|
4 |
|
5 | In computer science, this is known as an implementation of quasiquotes.
|
6 |
|
7 | ## Install
|
8 |
|
9 | ```sh
|
10 | npm install --save-dev babel-template
|
11 | ```
|
12 |
|
13 | ## Usage
|
14 |
|
15 | ```js
|
16 | import template from "babel-template";
|
17 | import generate from "babel-generator";
|
18 | import * as t from "babel-types";
|
19 |
|
20 | const buildRequire = template(`
|
21 | var IMPORT_NAME = require(SOURCE);
|
22 | `);
|
23 |
|
24 | const ast = buildRequire({
|
25 | IMPORT_NAME: t.identifier("myModule"),
|
26 | SOURCE: t.stringLiteral("my-module")
|
27 | });
|
28 |
|
29 | console.log(generate(ast).code);
|
30 | ```
|
31 |
|
32 | ```js
|
33 | const myModule = require("my-module");
|
34 | ```
|
35 |
|
36 | ## API
|
37 |
|
38 | ### `template(code, [opts])`
|
39 |
|
40 | #### code
|
41 |
|
42 | Type: `string`
|
43 |
|
44 | #### options
|
45 |
|
46 | `babel-template` accepts all of the options from [babylon], and specifies
|
47 | some defaults of its own:
|
48 |
|
49 | * `allowReturnOutsideFunction` is set to `true` by default.
|
50 | * `allowSuperOutsideMethod` is set to `true` by default.
|
51 |
|
52 | ##### preserveComments
|
53 |
|
54 | Type: `boolean`
|
55 | Default: `false`
|
56 |
|
57 | Set this to `true` to preserve any comments from the `code` parameter.
|
58 |
|
59 | #### Return value
|
60 |
|
61 | `babel-template` returns a `function` which is invoked with an optional object
|
62 | of replacements. See the usage section for an example.
|
63 |
|
64 | [babylon]: https://github.com/babel/babylon#options
|