A template literal is an ES2015 JavaScript string delimited by backticks. It supports multiline content and embedded expressions, making generated source code readable without escaping ordinary string delimiters. section 8.5 section 8.4
In a code generator, a template function can return a template literal containing the target file’s contents. The generator can then pass AST-derived data into that function and write the resulting string to a file. section 8.5 section 8.4
Generating runtime/index.jsx
Create indexJsx-template.js and export a function that returns the contents of runtime/index.jsx inside backticks. Call generatedIndexJsx(deserializedAst) from generate.js, then write the returned string. Running node src/generator/generate.js verifies that the generated file remains unchanged. section 8.4
Template literals offer these practical trade-offs:
- Use standard JavaScript and its language features without adding a template-framework dependency or separate syntax. section 8.4.5
- Handle indentation and formatting explicitly, unless nested strings or a separate formatter supplies that support. section 8.4.5 section 8.5
Table 8.1 Pros and cons of using template literals versus template frameworks
|
ES 2015 template literals
|
Other template framework
|
|
|---|---|---|
|
Pro
|
• Works out of the box.
• Uses standard JavaScript, so you can use all of JavaScript’s language features to properly engineer a code generator.
|
• May have a facility to help you with properly indenting the generated code. (Often, though, that facility depends on the availability of proper IDE support in the form of a plugin.)
|
|
Con
|
• All code formatting has to be done explicitly.
|
• It’s an extra dependency.
• Comes with its own syntax and peculiarities, which you’ll have to learn and understand.
• Your IDE of choice might not support a plugin for that framework that provides syntax checking and highlighting, content assist, etc.
• It may force you to precompute derived data, such as camel-cased names, separate from the actual template.
|
Compare built-in template literals with template frameworks across dependencies, syntax, IDE support, formatting, and derived-data handling. section 8.4.5


