feat(browser): inject script to js template

This commit is contained in:
Pooya Parsa 2020-11-05 22:56:40 +01:00
parent 6e1678316e
commit 04a25fc527
3 changed files with 20 additions and 22 deletions

View File

@ -7,7 +7,7 @@ import gzipSize from 'gzip-size'
import chalk from 'chalk'
import { emptyDir } from 'fs-extra'
import { getRollupConfig } from './rollup/config'
import { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils'
import { hl, prettyPath, renderTemplate, compileTemplateToJS, writeFileP } from './utils'
import { SLSOptions } from './config'
export async function build (options: SLSOptions) {
@ -17,7 +17,17 @@ export async function build (options: SLSOptions) {
const hooks = new Hookable()
hooks.addHooks(options.hooks)
await hooks.callHook('options', options)
// Compile html template
const htmlTemplate = {
src: resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[options.nuxt]}.template.html`),
dst: '',
compiled: ''
}
htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.')
htmlTemplate.compiled = await compileTemplateToJS(htmlTemplate.src)
await hooks.callHook('template:document', htmlTemplate)
await writeFileP(htmlTemplate.dst, htmlTemplate.compiled)
consola.info('Generated', prettyPath(htmlTemplate.dst))
emptyDir(options.slsDir)
@ -44,10 +54,3 @@ export async function build (options: SLSOptions) {
await hooks.callHook('done', options)
}
export async function compileHTMLTemplate (options: SLSOptions) {
const htmlTemplateFile = resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[options.nuxt]}.template.html`)
const htmlTemplateFileJS = htmlTemplateFile.replace(/.html$/, '.js').replace('app.', 'document.')
await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS)
consola.info('Generated', prettyPath(htmlTemplateFileJS))
}

View File

@ -41,13 +41,5 @@ export default <Module> function slsModule () {
}
})
nuxt.hook('generate:done', () => buildSLS(options))
}
async function buildSLS (options) {
// Compile html template
await compileHTMLTemplate(options)
// Bundle target
await build(options)
nuxt.hook('generate:done', () => build(options))
}

View File

@ -24,12 +24,15 @@ export async function renderTemplate (src: string, dst: string, params: any) {
await writeFile(dst, rendered)
}
export async function compileTemplateToJS (src: string, dst: string) {
export async function compileTemplateToJS (src: string) {
const contents = await readFile(src, 'utf-8')
// eslint-disable-next-line no-template-curly-in-string
const compiled = `export default (params) => \`${contents.replace(/{{ (\w+) }}/g, '${params.$1}')}\``
await mkdirp(dirname(dst))
await writeFile(dst, compiled)
return `export default (params) => \`${contents.replace(/{{ (\w+) }}/g, '${params.$1}')}\``
}
export async function writeFileP (path, contents) {
await mkdirp(dirname(path))
await writeFile(path, contents)
}
export const jitiImport = (dir: string, path: string) => jiti(dir)(path)