A nested string is a string or arbitrarily deep array of strings, including multiline strings. Template functions return this flexible structure instead of manually concatenating fragments or joining lines. section 8.4.2
Array construction replaces both string concatenation and newline joining. The generator can compose template results declaratively, then convert the outermost structure into a writable string. section 8.4.2 section 8.5
Generating a React rental form
The indexJsx template returns imports, a mapped array of attribute initializers, and trailing code as one nested structure. asString flattens arrays, ensures newline endings, and joins the fragments before writing the generated file. section 8.4.2
Listing 8.14 The asString function in src/generator/template-utils.js
const withNewlineEnsured = (str) => str #1
+ (str.endsWith("\n") ? "" : "\n")
const asString = (nestedString) =>
Array.isArray(nestedString) #2
? nestedString.flat(Infinity) #3
.map(withNewlineEnsured) #4
.join("") #5
: withNewlineEnsured(nestedString) #6
module.exports.asString = asString #7
Inspect the asString implementation that recursively flattens nested arrays, normalizes newline endings, and joins the resulting strings. section 8.4.2
