Skip to content

Commit

Permalink
Merge acdee9b into c79b691
Browse files Browse the repository at this point in the history
  • Loading branch information
mbland committed Nov 29, 2023
2 parents c79b691 + acdee9b commit c3c12e6
Showing 1 changed file with 44 additions and 34 deletions.
78 changes: 44 additions & 34 deletions strcalc/src/main/frontend/rollup-plugin-handlebars-precompile.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,46 +44,56 @@ const PLUGIN_ID = `\0${PLUGIN_NAME}`
const HANDLEBARS_PATH = 'handlebars/lib/handlebars.runtime'
const IMPORT_HANDLEBARS = `import Handlebars from '${HANDLEBARS_PATH}'`

function helpersModule(helpers) {
return [
IMPORT_HANDLEBARS,
...helpers.map((h, i) => `import registerHelpers${i} from './${h}'`),
...helpers.map((_, i) => `registerHelpers${i}(Handlebars)`)
].join('\n')
}

function compiledModule(code, options, helpers) {
const compiled = Handlebars.precompile(code, options)
let imports = helpers.length ? [`import '${PLUGIN_ID}'`] : []
class PluginImpl {
#options
#helpers
#isTemplate

return [
IMPORT_HANDLEBARS,
...imports,
`export default Handlebars.template(${compiled.toString()})`
].join('\n')
}
constructor(options = {}) {
this.#options = options
this.#helpers = options.helpers || []
this.#isTemplate = createFilter(
options.include || DEFAULT_INCLUDE,
options.exclude || DEFAULT_EXCLUDE
)
}

export default function (options = {}) {
const isTemplate = createFilter(
options.include || DEFAULT_INCLUDE,
options.exclude || DEFAULT_EXCLUDE
)
const helpers = options.helpers || []
const shouldEmitHelpersModule = id => id === PLUGIN_ID && helpers.length
shouldEmitHelpersModule(id) {
return id === PLUGIN_ID && this.#helpers.length
}

return {
name: PLUGIN_NAME,
helpersModule() {
const helpers = this.#helpers
return [
IMPORT_HANDLEBARS,
...helpers.map((h, i) => `import registerHelpers${i} from './${h}'`),
...helpers.map((_, i) => `registerHelpers${i}(Handlebars)`)
].join('\n')
}

resolveId(id) { if (shouldEmitHelpersModule(id)) return id },
isTemplate(id) { return this.#isTemplate(id) }

load(id) {
if (shouldEmitHelpersModule(id)) return helpersModule(helpers)
},
compiledModule(code) {
const precompiled = Handlebars.precompile(code, this.#options)
let imports = this.#helpers.length ? [`import '${PLUGIN_ID}'`] : []

transform(code, id) {
if (isTemplate(id)) return {
code: compiledModule(code, options, helpers)
}
return {
code: [
IMPORT_HANDLEBARS,
...imports,
`export default Handlebars.template(${precompiled.toString()})`
].join('\n')
}
}
}

export default function(options) {
const p = new PluginImpl(options)

return {
name: PLUGIN_NAME,
resolveId(id) { if (p.shouldEmitHelpersModule(id)) return id },
load(id) { if (p.shouldEmitHelpersModule(id)) return p.helpersModule() },
transform(code, id) { if (p.isTemplate(id)) return p.compiledModule(code) }
}
}

0 comments on commit c3c12e6

Please sign in to comment.