Nuxt/packages/builder/src/builder.js

714 lines
21 KiB
JavaScript
Raw Normal View History

2018-03-16 19:52:17 +00:00
import path from 'path'
2018-03-16 16:12:06 +00:00
import chokidar from 'chokidar'
import consola from 'consola'
2018-03-16 19:11:24 +00:00
import fsExtra from 'fs-extra'
import Glob from 'glob'
2018-03-16 16:12:06 +00:00
import hash from 'hash-sum'
import pify from 'pify'
2018-03-16 19:52:17 +00:00
import upath from 'upath'
import semver from 'semver'
import debounce from 'lodash/debounce'
import omit from 'lodash/omit'
import template from 'lodash/template'
import uniq from 'lodash/uniq'
import uniqBy from 'lodash/uniqBy'
2018-03-16 19:52:17 +00:00
import {
r,
createRoutes,
relativeTo,
waitFor,
2018-10-24 13:46:06 +00:00
determineGlobals,
2018-10-25 10:57:52 +00:00
stripWhitespace,
isString,
isIndexFileAndFolder,
isPureObject,
clearRequireCache
2018-12-22 21:05:13 +00:00
} from '@nuxt/utils'
2018-03-16 19:52:17 +00:00
2019-01-29 09:31:14 +00:00
import Ignore from './ignore'
import BuildContext from './context/build'
import TemplateContext from './context/template'
const glob = pify(Glob)
2018-03-16 16:12:06 +00:00
export default class Builder {
constructor(nuxt, bundleBuilder) {
2017-06-11 14:17:36 +00:00
this.nuxt = nuxt
this.plugins = []
2017-06-11 14:17:36 +00:00
this.options = nuxt.options
this.globals = determineGlobals(nuxt.options.globalName, nuxt.options.globals)
this.watchers = {
files: null,
custom: null,
restart: null
}
2018-12-22 22:42:20 +00:00
this.supportedExtensions = ['vue', 'js', 'ts', 'tsx']
// Helper to resolve build paths
this.relativeToBuild = (...args) => relativeTo(this.options.buildDir, ...args)
this._buildStatus = STATUS.INITIAL
2018-11-08 09:15:56 +00:00
// Hooks for watch lifecycle
2017-11-24 03:43:01 +00:00
if (this.options.dev) {
2018-11-08 09:15:56 +00:00
// Start watching after initial render
this.nuxt.hook('build:done', () => {
consola.info('Waiting for file changes')
this.watchClient()
this.watchRestart()
2018-11-08 09:15:56 +00:00
})
// Close hook
this.nuxt.hook('close', () => this.close())
2018-03-22 19:29:05 +00:00
}
if (this.options.build.analyze) {
this.nuxt.hook('build:done', () => {
consola.warn('Notice: Please do not deploy bundles built with analyze mode, it\'s only for analyzing purpose.')
})
}
// Resolve template
this.template = this.options.build.template || '@nuxt/vue-app'
if (typeof this.template === 'string') {
this.template = this.nuxt.resolver.requireModule(this.template).template
}
// Create a new bundle builder
this.bundleBuilder = this.getBundleBuilder(bundleBuilder)
2019-01-29 09:31:14 +00:00
this.ignore = new Ignore({
rootDir: this.options.srcDir
})
}
getBundleBuilder(BundleBuilder) {
if (typeof BundleBuilder === 'object') {
return BundleBuilder
}
const context = new BuildContext(this)
if (typeof BundleBuilder !== 'function') {
({ BundleBuilder } = require('@nuxt/webpack'))
}
return new BundleBuilder(context)
2017-06-11 14:17:36 +00:00
}
2017-10-30 17:41:22 +00:00
forGenerate() {
this.bundleBuilder.forGenerate()
2017-08-17 12:43:51 +00:00
}
2017-10-30 17:41:22 +00:00
async build() {
// Avoid calling build() method multiple times when dev:true
if (this._buildStatus === STATUS.BUILD_DONE && this.options.dev) {
2017-06-11 14:17:36 +00:00
return this
}
// If building
if (this._buildStatus === STATUS.BUILDING) {
await waitFor(1000)
return this.build()
2017-06-11 14:17:36 +00:00
}
this._buildStatus = STATUS.BUILDING
2017-06-13 17:58:04 +00:00
2018-11-08 09:15:56 +00:00
if (this.options.dev) {
consola.info('Preparing project for development')
consola.info('Initial build may take a while')
} else {
consola.info('Production build')
}
2018-03-12 15:16:08 +00:00
// Wait for nuxt ready
await this.nuxt.ready()
2017-10-30 21:39:08 +00:00
// Call before hook
await this.nuxt.callHook('build:before', this, this.options.build)
2017-07-03 11:11:40 +00:00
await this.validatePages()
2017-06-13 17:58:04 +00:00
// Validate template
try {
this.validateTemplate()
} catch (err) {
consola.fatal(err)
}
2018-04-01 20:20:46 +00:00
consola.success('Builder initialized')
2018-03-16 06:26:23 +00:00
2018-04-01 20:20:46 +00:00
consola.debug(`App root: ${this.options.srcDir}`)
2017-06-11 14:17:36 +00:00
// Create .nuxt/, .nuxt/components and .nuxt/dist folders
2018-03-16 19:11:24 +00:00
await fsExtra.remove(r(this.options.buildDir))
const buildDirs = [r(this.options.buildDir, 'components')]
2017-06-11 14:17:36 +00:00
if (!this.options.dev) {
buildDirs.push(
r(this.options.buildDir, 'dist', 'client'),
r(this.options.buildDir, 'dist', 'server')
)
2017-06-11 14:17:36 +00:00
}
await Promise.all(buildDirs.map(dir => fsExtra.mkdirp(dir)))
2017-06-11 14:17:36 +00:00
// Generate routes and interpret the template files
await this.generateRoutesAndFiles()
await this.resolvePlugins()
// Start bundle build: webpack, rollup, parcel...
await this.bundleBuilder.build()
2017-06-11 14:17:36 +00:00
// Flag to set that building is done
this._buildStatus = STATUS.BUILD_DONE
2017-10-30 21:39:08 +00:00
// Call done hook
await this.nuxt.callHook('build:done', this)
2017-10-30 17:41:22 +00:00
2017-06-11 14:17:36 +00:00
return this
}
// Check if pages dir exists and warn if not
async validatePages() {
this._nuxtPages = typeof this.options.build.createRoutes !== 'function'
if (
!this._nuxtPages ||
await fsExtra.exists(path.join(this.options.srcDir, this.options.dir.pages))
) {
return
}
const dir = this.options.srcDir
if (await fsExtra.exists(path.join(this.options.srcDir, '..', this.options.dir.pages))) {
throw new Error(
`No \`${this.options.dir.pages}\` directory found in ${dir}. Did you mean to run \`nuxt\` in the parent (\`../\`) directory?`
)
}
this._defaultPage = true
consola.warn(`No \`${this.options.dir.pages}\` directory found in ${dir}. Using the default built-in page.`)
}
validateTemplate() {
// Validate template dependencies
const templateDependencies = this.template.dependencies
for (const depName in templateDependencies) {
const depVersion = templateDependencies[depName]
// Load installed version
const pkg = this.nuxt.resolver.requireModule(path.join(depName, 'package.json'))
if (pkg) {
const validVersion = semver.satisfies(pkg.version, depVersion)
if (!validVersion) {
consola.warn(`${depName}@${depVersion} is recommended but ${depName}@${pkg.version} is installed!`)
}
} else {
consola.warn(`${depName}@${depVersion} is required but not installed!`)
}
}
}
globPathWithExtensions(path) {
return `${path}/**/*.{${this.supportedExtensions.join(',')}}`
}
2017-10-30 17:41:22 +00:00
async generateRoutesAndFiles() {
consola.debug('Generating nuxt files')
// Plugins
this.plugins = Array.from(this.normalizePlugins())
const templateContext = new TemplateContext(this, this.options)
await Promise.all([
this.resolveLayouts(templateContext),
this.resolveRoutes(templateContext),
this.resolveStore(templateContext),
this.resolveMiddleware(templateContext)
])
await this.resolveCustomTemplates(templateContext)
await this.resolveLoadingIndicator(templateContext)
// Add vue-app template dir to watchers
this.options.build.watch.push(this.globPathWithExtensions(this.template.dir))
await this.compileTemplates(templateContext)
consola.success('Nuxt files generated')
}
normalizePlugins() {
const modes = ['client', 'server']
const modePattern = new RegExp(`\\.(${modes.join('|')})(\\.\\w+)*$`)
return uniqBy(
this.options.plugins.map((p) => {
if (typeof p === 'string') {
p = { src: p }
}
const pluginBaseName = path.basename(p.src, path.extname(p.src)).replace(
/[^a-zA-Z?\d\s:]/g,
''
)
2017-06-11 14:17:36 +00:00
if (p.ssr === false) {
p.mode = 'client'
} else if (p.mode === undefined) {
p.mode = 'all'
p.src.replace(modePattern, (_, mode) => {
if (modes.includes(mode)) {
p.mode = mode
}
})
} else if (!['client', 'server', 'all'].includes(p.mode)) {
consola.warn(`Invalid plugin mode (server/client/all): '${p.mode}'. Falling back to 'all'`)
p.mode = 'all'
}
return {
src: this.nuxt.resolver.resolveAlias(p.src),
mode: p.mode,
name: 'nuxt_plugin_' + pluginBaseName + '_' + hash(p.src)
}
}),
p => p.name
)
}
async resolveFiles(dir, cwd = this.options.srcDir) {
return this.ignore.filter(await glob(this.globPathWithExtensions(dir), {
cwd,
ignore: this.options.ignore
}))
}
async resolveRelative(dir) {
const dirPrefix = new RegExp(`^${dir}/`)
return (await this.resolveFiles(dir)).map(file => ({ src: file.replace(dirPrefix, '') }))
}
async resolveLayouts({ templateVars, templateFiles }) {
if (await fsExtra.exists(path.resolve(this.options.srcDir, this.options.dir.layouts))) {
for (const file of await this.resolveFiles(this.options.dir.layouts)) {
2018-08-08 10:54:05 +00:00
const name = file
.replace(new RegExp(`^${this.options.dir.layouts}/`), '')
.replace(new RegExp(`\\.(${this.supportedExtensions.join('|')})$`), '')
// Layout Priority: module.addLayout > .vue file > other extensions
2017-08-14 12:15:00 +00:00
if (name === 'error') {
if (!templateVars.components.ErrorPage) {
templateVars.components.ErrorPage = this.relativeToBuild(
this.options.srcDir,
file
)
}
} else if (this.options.layouts[name]) {
consola.warn(`Duplicate layout registration, "${name}" has been registered as "${this.options.layouts[name]}"`)
} else if (!templateVars.layouts[name] || /\.vue$/.test(file)) {
2018-01-13 05:22:11 +00:00
templateVars.layouts[name] = this.relativeToBuild(
this.options.srcDir,
file
)
}
}
2017-06-11 14:17:36 +00:00
}
2017-06-11 14:17:36 +00:00
// If no default layout, create its folder and add the default folder
if (!templateVars.layouts.default) {
2018-03-16 19:11:24 +00:00
await fsExtra.mkdirp(r(this.options.buildDir, 'layouts'))
templateFiles.push('layouts/default.vue')
2017-06-20 17:12:06 +00:00
templateVars.layouts.default = './layouts/default.vue'
2017-06-11 14:17:36 +00:00
}
}
2017-06-11 14:17:36 +00:00
async resolveRoutes({ templateVars }) {
2018-04-01 20:20:46 +00:00
consola.debug('Generating routes...')
if (this._defaultPage) {
templateVars.router.routes = createRoutes(
['index.vue'],
this.template.dir + '/pages',
'',
this.options.router.routeNameSplitter
)
} else if (this._nuxtPages) {
2017-06-11 14:17:36 +00:00
// Use nuxt.js createRoutes bases on pages/
2018-01-13 05:22:11 +00:00
const files = {}
2019-01-29 09:31:14 +00:00
const ext = new RegExp(`\\.(${this.supportedExtensions.join('|')})$`)
for (const page of await this.resolveFiles(this.options.dir.pages)) {
const key = page.replace(ext, '')
// .vue file takes precedence over other extensions
2019-01-29 09:31:14 +00:00
if (/\.vue$/.test(page) || !files[key]) {
files[key] = page.replace(/(['"])/g, '\\$1')
}
2019-01-29 09:31:14 +00:00
}
2018-01-13 05:22:11 +00:00
templateVars.router.routes = createRoutes(
Object.values(files),
2018-02-02 16:58:51 +00:00
this.options.srcDir,
this.options.dir.pages,
this.options.router.routeNameSplitter
2018-01-13 05:22:11 +00:00
)
} else { // If user defined a custom method to create routes
2018-01-13 05:22:11 +00:00
templateVars.router.routes = this.options.build.createRoutes(
this.options.srcDir
)
2017-06-11 14:17:36 +00:00
}
2017-07-03 11:11:40 +00:00
2018-01-13 05:22:11 +00:00
await this.nuxt.callHook(
'build:extendRoutes',
templateVars.router.routes,
r
)
2017-06-11 14:17:36 +00:00
// router.extendRoutes method
if (typeof this.options.router.extendRoutes === 'function') {
// let the user extend the routes
2018-01-13 05:22:11 +00:00
const extendedRoutes = this.options.router.extendRoutes(
templateVars.router.routes,
r
)
// Only overwrite routes when something is returned for backwards compatibility
if (extendedRoutes !== undefined) {
templateVars.router.routes = extendedRoutes
}
2017-06-11 14:17:36 +00:00
}
// Make routes accessible for other modules and webpack configs
this.routes = templateVars.router.routes
}
async resolveStore({ templateVars, templateFiles }) {
2017-06-11 14:17:36 +00:00
// Add store if needed
if (!this.options.store) {
return
2017-06-11 14:17:36 +00:00
}
templateVars.storeModules = (await this.resolveRelative(this.options.dir.store))
.sort(({ src: p1 }, { src: p2 }) => {
// modules are sorted from low to high priority (for overwriting properties)
let res = p1.split('/').length - p2.split('/').length
if (res === 0 && p1.includes('/index.')) {
res = -1
} else if (res === 0 && p2.includes('/index.')) {
res = 1
}
return res
})
templateFiles.push('store.js')
}
2017-06-11 14:17:36 +00:00
async resolveMiddleware({ templateVars }) {
2019-01-29 09:31:14 +00:00
// -- Middleware --
templateVars.middleware = await this.resolveRelative(this.options.dir.middleware)
}
2019-01-29 09:31:14 +00:00
async resolveCustomTemplates(templateContext) {
2017-06-11 14:17:36 +00:00
// Resolve template files
2018-01-13 05:22:11 +00:00
const customTemplateFiles = this.options.build.templates.map(
2018-03-16 19:11:24 +00:00
t => t.dst || path.basename(t.src || t)
2018-01-13 05:22:11 +00:00
)
const templateFiles = await Promise.all(templateContext.templateFiles.map(async (file) => {
// Skip if custom file was already provided in build.templates[]
if (customTemplateFiles.includes(file)) {
return
}
// Allow override templates using a file with same name in ${srcDir}/app
const customPath = r(this.options.srcDir, 'app', file)
const customFileExists = await fsExtra.exists(customPath)
return {
src: customFileExists ? customPath : r(this.template.dir, file),
dst: file,
custom: customFileExists
}
}))
2018-01-13 05:22:11 +00:00
templateContext.templateFiles = templateFiles
2018-10-25 10:57:52 +00:00
.filter(Boolean)
// Add custom template files
.concat(
this.options.build.templates.map((t) => {
return Object.assign(
{
src: r(this.options.srcDir, t.src || t),
dst: t.dst || path.basename(t.src || t),
custom: true
},
typeof t === 'object' ? t : undefined
)
})
)
}
2017-06-11 14:17:36 +00:00
async resolveLoadingIndicator({ templateFiles }) {
if (!this.options.loadingIndicator.name) {
return
}
let indicatorPath = path.resolve(
this.template.dir,
'views/loading',
this.options.loadingIndicator.name + '.html'
)
let customIndicator = false
if (!await fsExtra.exists(indicatorPath)) {
indicatorPath = this.nuxt.resolver.resolveAlias(
this.options.loadingIndicator.name
)
if (await fsExtra.exists(indicatorPath)) {
customIndicator = true
2017-08-18 12:23:10 +00:00
} else {
indicatorPath = null
2017-08-18 10:26:19 +00:00
}
}
if (!indicatorPath) {
consola.error(
`Could not fetch loading indicator: ${
this.options.loadingIndicator.name
}`
)
return
}
templateFiles.push({
src: indicatorPath,
dst: 'loading.html',
custom: customIndicator,
options: this.options.loadingIndicator
})
}
async compileTemplates(templateContext) {
// Prepare template options
const { templateVars, templateFiles, templateOptions } = templateContext
2017-08-18 10:26:19 +00:00
2018-01-13 05:22:11 +00:00
await this.nuxt.callHook('build:templates', {
templateVars,
2019-02-01 11:56:26 +00:00
templatesFiles: templateFiles,
2018-01-13 05:22:11 +00:00
resolve: r
})
2017-07-03 11:11:40 +00:00
templateOptions.imports = {
...templateOptions.imports,
resolvePath: this.nuxt.resolver.resolvePath,
resolveAlias: this.nuxt.resolver.resolveAlias,
relativeToBuild: this.relativeToBuild
}
2017-06-11 14:17:36 +00:00
// Interpret and move template files to .nuxt/
2018-01-13 05:22:11 +00:00
await Promise.all(
templateFiles.map(async (templateFile) => {
const { src, dst, custom } = templateFile
// Add custom templates to watcher
if (custom) {
this.options.build.watch.push(src)
}
2018-01-13 05:22:11 +00:00
// Render template to dst
2018-03-16 19:11:24 +00:00
const fileContent = await fsExtra.readFile(src, 'utf8')
2018-01-13 05:22:11 +00:00
let content
try {
const templateFunction = template(fileContent, templateOptions)
2018-10-24 13:46:06 +00:00
content = stripWhitespace(
templateFunction({
...templateVars,
...templateFile
})
2018-01-13 05:22:11 +00:00
)
} catch (err) {
throw new Error(`Could not compile template ${src}: ${err.message}`)
}
// Ensure parent dir exits and write file
const relativePath = r(this.options.buildDir, dst)
await fsExtra.outputFile(relativePath, content, 'utf8')
2018-01-13 05:22:11 +00:00
})
)
}
resolvePlugins() {
// Check plugins exist then set alias to their real path
return Promise.all(this.plugins.map(async (p) => {
const ext = '{?(.+([^.])),/index.+([^.])}'
const pluginFiles = await glob(`${p.src}${ext}`)
if (!pluginFiles || pluginFiles.length === 0) {
throw new Error(`Plugin not found: ${p.src}`)
}
if (pluginFiles.length > 1 && !isIndexFileAndFolder(pluginFiles)) {
consola.warn({
message: `Found ${pluginFiles.length} plugins that match the configuration, suggest to specify extension:`,
additional: '\n' + pluginFiles.map(x => `- ${x}`).join('\n')
})
}
p.src = this.relativeToBuild(p.src)
}))
2017-06-11 14:17:36 +00:00
}
// TODO: Uncomment when generateConfig enabled again
// async generateConfig() {
// const config = path.resolve(this.options.buildDir, 'build.config.js')
// const options = omit(this.options, Options.unsafeKeys)
// await fsExtra.writeFile(
// config,
// `export default ${JSON.stringify(options, null, ' ')}`,
// 'utf8'
// )
// }
2017-06-11 14:17:36 +00:00
createFileWatcher(patterns, events, listener, watcherCreatedCallback) {
const options = this.options.watchers.chokidar
const watcher = chokidar.watch(patterns, options)
for (const event of events) {
watcher.on(event, listener)
}
// TODO: due to fixes in chokidar this isnt used anymore and could be removed in Nuxt v3
const { rewatchOnRawEvents } = this.options.watchers
if (rewatchOnRawEvents && Array.isArray(rewatchOnRawEvents)) {
watcher.on('raw', (_event) => {
if (rewatchOnRawEvents.includes(_event)) {
watcher.close()
listener()
this.createFileWatcher(patterns, events, listener, watcherCreatedCallback)
}
})
}
if (typeof watcherCreatedCallback === 'function') {
watcherCreatedCallback(watcher)
}
}
assignWatcher(key) {
return (watcher) => {
this.watchers[key] = watcher
}
}
2018-08-15 11:48:34 +00:00
watchClient() {
2018-01-02 02:36:09 +00:00
let patterns = [
r(this.options.srcDir, this.options.dir.layouts),
r(this.options.srcDir, this.options.dir.middleware)
2017-06-11 14:17:36 +00:00
]
if (this.options.store) {
patterns.push(r(this.options.srcDir, this.options.dir.store))
}
if (this._nuxtPages && !this._defaultPage) {
patterns.push(r(this.options.srcDir, this.options.dir.pages))
2017-11-24 08:21:08 +00:00
}
patterns = patterns.map((path, ...args) => upath.normalizeSafe(this.globPathWithExtensions(path), ...args))
2018-01-02 02:36:09 +00:00
const refreshFiles = debounce(() => this.generateRoutesAndFiles(), 200)
2017-06-15 22:19:53 +00:00
// Watch for src Files
this.createFileWatcher(patterns, ['add', 'unlink'], refreshFiles, this.assignWatcher('files'))
2017-06-15 22:19:53 +00:00
2017-06-11 14:17:36 +00:00
// Watch for custom provided files
const customPatterns = uniq([
...this.options.build.watch,
...Object.values(omit(this.options.build.styleResources, ['options']))
]).map(upath.normalizeSafe)
if (customPatterns.length === 0) {
return
}
this.createFileWatcher(customPatterns, ['change'], refreshFiles, this.assignWatcher('custom'))
2018-08-15 11:48:34 +00:00
}
getServerMiddlewarePaths() {
return this.options.serverMiddleware
.map((serverMiddleware) => {
if (isString(serverMiddleware)) {
return serverMiddleware
}
if (isPureObject(serverMiddleware) && isString(serverMiddleware.handler)) {
return serverMiddleware.handler
}
})
.filter(Boolean)
.map(p => path.extname(p) ? p : this.nuxt.resolver.resolvePath(p))
}
watchRestart() {
const serverMiddlewarePaths = this.getServerMiddlewarePaths()
const nuxtRestartWatch = [
// Server middleware
...serverMiddlewarePaths,
// Custom watchers
...this.options.watch
].map(this.nuxt.resolver.resolveAlias)
2018-08-15 11:48:34 +00:00
2019-01-29 09:31:14 +00:00
if (this.ignore.ignoreFile) {
nuxtRestartWatch.push(this.ignore.ignoreFile)
}
// If default page displayed, watch for first page creation
if (this._nuxtPages && this._defaultPage) {
nuxtRestartWatch.push(path.join(this.options.srcDir, this.options.dir.pages))
}
// If store not activated, watch for a file in the directory
if (!this.options.store) {
nuxtRestartWatch.push(path.join(this.options.srcDir, this.options.dir.store))
}
2019-01-29 09:31:14 +00:00
this.createFileWatcher(
nuxtRestartWatch,
['all'],
async (event, fileName) => {
if (['add', 'change', 'unlink'].includes(event) === false) {
return
}
/* istanbul ignore if */
if (serverMiddlewarePaths.includes(fileName)) {
consola.debug(`Clear cache for ${fileName}`)
clearRequireCache(fileName)
}
await this.nuxt.callHook('watch:fileChanged', this, fileName) // Legacy
await this.nuxt.callHook('watch:restart', { event, path: fileName })
},
this.assignWatcher('restart')
)
2017-06-11 14:17:36 +00:00
}
2017-11-24 03:43:01 +00:00
unwatch() {
for (const watcher in this.watchers) {
this.watchers[watcher].close()
}
}
async close() {
if (this.__closed) {
return
}
this.__closed = true
// Unwatch
this.unwatch()
// Close bundleBuilder
if (typeof this.bundleBuilder.close === 'function') {
await this.bundleBuilder.close()
}
2017-11-24 03:43:01 +00:00
}
2017-06-11 14:17:36 +00:00
}
const STATUS = {
INITIAL: 1,
BUILD_DONE: 2,
BUILDING: 3
}