Nuxt/packages/nuxt3/src/builder/builder.ts

93 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-08-17 18:02:10 +00:00
import { join } from 'path'
import fsExtra from 'fs-extra'
2020-08-04 10:06:44 +00:00
import { BundleBuilder } from 'src/webpack'
import { Nuxt } from '../core'
2020-08-17 18:02:10 +00:00
import { compileTemplates, scanTemplates, NuxtTemplate } from './template'
import { createWatcher } from './watch'
import { resolveApp, NuxtApp } from './app'
2020-07-02 13:02:35 +00:00
export class Builder {
2020-07-30 23:40:16 +00:00
nuxt: Nuxt
app: NuxtApp
2020-08-17 18:02:10 +00:00
templates: NuxtTemplate[]
2020-08-04 10:26:22 +00:00
constructor (nuxt) {
2020-07-02 13:02:35 +00:00
this.nuxt = nuxt
}
build () {
return build(this)
2020-07-02 13:02:35 +00:00
}
}
2020-07-02 13:02:35 +00:00
// Extends VueRouter
2020-08-17 18:02:10 +00:00
async function build(builder: Builder) {
const { nuxt } = builder
2020-07-02 13:02:35 +00:00
2020-08-17 18:02:10 +00:00
await generate(builder)
if (nuxt.options.dev) {
watch(builder)
}
2020-07-02 13:02:35 +00:00
await bundle(builder)
2020-07-02 13:02:35 +00:00
}
2020-08-17 18:02:10 +00:00
function watch(builder: Builder) {
const { nuxt } = builder
// Watch internal templates
const nuxtAppWatcher = createWatcher(nuxt.options.appDir)
// nuxtAppWatcher.debug()
nuxtAppWatcher.watchAll(async () => {
console.log('Re-generate templates')
await compileTemplates(builder.templates, nuxt.options.buildDir)
})
// Watch user app
const appWatcher = createWatcher(builder.app.srcDir, {
ignored: [
nuxt.options.buildDir
]
})
// appWatcher.debug()
appWatcher.watch(/(A|a)pp\.[a-z]{2,3}/, async () => {
await new Promise((resolve) => setTimeout(resolve, 200))
await generate(builder)
})
appWatcher.watch('pages/', async () => {
console.log('Re-generate routes')
await compileTemplates(builder.templates, nuxt.options.buildDir)
})
}
export async function generate(builder: Builder) {
const { nuxt } = builder
await fsExtra.mkdirp(nuxt.options.buildDir)
builder.app = resolveApp(nuxt, nuxt.options.srcDir)
const templatesDir = join(builder.nuxt.options.appDir, '_templates')
const appTemplates = await scanTemplates(templatesDir, {
app: builder.app
})
builder.templates = [
...appTemplates
]
await compileTemplates(builder.templates, nuxt.options.buildDir)
}
async function bundle ({ nuxt }: Builder) {
// TODO: get rid of this context and directly pass nuxt to BundleBuilder
const bundleBuilder = new BundleBuilder({
nuxt,
options: nuxt.options,
buildOptions: nuxt.options.build,
target: nuxt.options.target,
plugins: []
})
await bundleBuilder.build()
}