27142ff04c79e200073f5560cf507e6c36e0c88f6c34d198ebfc99e3631e7821b0770473bd728b5a635a12309aa9709ec7c601bc595ccbd4a15a9737a4da22 1.2 KB

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