UNPKG

1.23 kBMarkdownView Raw
1# babel-template
2
3> Generate an AST from a string template.
4
5In computer science, this is known as an implementation of quasiquotes.
6
7## Install
8
9```sh
10npm install --save-dev babel-template
11```
12
13## Usage
14
15```js
16import template from "babel-template";
17import generate from "babel-generator";
18import * as t from "babel-types";
19
20const buildRequire = template(`
21 var IMPORT_NAME = require(SOURCE);
22`);
23
24const ast = buildRequire({
25 IMPORT_NAME: t.identifier("myModule"),
26 SOURCE: t.stringLiteral("my-module")
27});
28
29console.log(generate(ast).code);
30```
31
32```js
33const myModule = require("my-module");
34```
35
36## API
37
38### `template(code, [opts])`
39
40#### code
41
42Type: `string`
43
44#### options
45
46`babel-template` accepts all of the options from [babylon], and specifies
47some 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
54Type: `boolean`
55Default: `false`
56
57Set 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
62of replacements. See the usage section for an example.
63
64[babylon]: https://github.com/babel/babylon#options