Nuxt/lib/builder/builder.js

549 lines
17 KiB
JavaScript
Raw Normal View History

2017-06-11 14:17:36 +00:00
import _ from 'lodash'
import chokidar from 'chokidar'
import fs, { remove, readFile, writeFile, mkdirp, existsSync } from 'fs-extra'
2017-06-11 14:17:36 +00:00
import hash from 'hash-sum'
import pify from 'pify'
import webpack from 'webpack'
import serialize from 'serialize-javascript'
import { join, resolve, basename, extname, dirname } from 'path'
2017-06-15 22:19:53 +00:00
import MFS from 'memory-fs'
2017-06-16 12:42:45 +00:00
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import { r, wp, wChunk, createRoutes, sequence, relativeTo, isPureObject } from 'utils'
2017-06-18 09:35:00 +00:00
import Debug from 'debug'
import Glob from 'glob'
2017-06-11 14:17:36 +00:00
import clientWebpackConfig from './webpack/client.config.js'
import serverWebpackConfig from './webpack/server.config.js'
import dllWebpackConfig from './webpack/dll.config.js'
2017-08-14 14:03:07 +00:00
import vueLoaderConfig from './webpack/vue-loader.config'
import styleLoader from './webpack/style-loader'
2017-06-11 14:17:36 +00:00
2017-06-18 09:35:00 +00:00
const debug = Debug('nuxt:build')
2017-06-11 14:17:36 +00:00
debug.color = 2 // Force green color
2017-06-18 09:35:00 +00:00
const glob = pify(Glob)
2017-06-11 14:17:36 +00:00
2017-10-30 21:39:08 +00:00
export default class Builder {
2017-10-30 17:41:22 +00:00
constructor(nuxt) {
2017-06-11 14:17:36 +00:00
this.nuxt = nuxt
this.isStatic = false // Flag to know if the build is for a generated app
2017-06-11 14:17:36 +00:00
this.options = nuxt.options
// Fields that set on build
2017-11-07 09:46:29 +00:00
this.compilers = []
this.webpackDevMiddleware = null
this.webpackHotMiddleware = null
// Mute stats on dev
2017-06-15 22:19:53 +00:00
this.webpackStats = this.options.dev ? false : {
2017-06-11 14:17:36 +00:00
chunks: false,
children: false,
modules: false,
2017-08-10 10:57:54 +00:00
colors: true,
excludeAssets: [
/.map$/,
/index\..+\.html$/,
/vue-ssr-client-manifest.json/
]
2017-06-11 14:17:36 +00:00
}
// Helper to resolve build paths
this.relativeToBuild = (...args) => relativeTo(this.options.buildDir, ...args)
2017-08-14 14:03:07 +00:00
// Bind styleLoader and vueLoader
this.styleLoader = styleLoader.bind(this)
this.vueLoader = vueLoaderConfig.bind(this)
this._buildStatus = STATUS.INITIAL
2017-06-11 14:17:36 +00:00
}
2017-10-30 17:41:22 +00:00
get plugins() {
2017-07-10 22:53:06 +00:00
return this.options.plugins.map((p, i) => {
if (typeof p === 'string') p = { src: p }
return {
src: this.nuxt.resolvePath(p.src),
ssr: (p.ssr !== false),
name: basename(p.src, extname(p.src)).replace(/[^a-zA-Z?\d\s:]/g, '') + '_plugin_' + hash(p.src)
}
2017-07-10 22:53:06 +00:00
})
}
2017-10-30 17:41:22 +00:00
vendor() {
return [
'vue',
'vue-router',
'vue-meta',
2017-08-21 19:12:41 +00:00
this.options.store && 'vuex'
].concat(this.options.build.vendor).filter(v => v)
}
2017-10-30 17:41:22 +00:00
vendorEntries() {
// Used for dll
const vendor = this.vendor()
const vendorEntries = {}
vendor.forEach(v => {
2017-08-21 19:40:06 +00:00
try {
require.resolve(v)
vendorEntries[v] = [ v ]
} catch (e) {
// Ignore
}
})
return vendorEntries
}
2017-10-30 17:41:22 +00:00
forGenerate() {
this.isStatic = true
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
2017-06-19 15:47:31 +00:00
/* istanbul ignore if */
if (this._buildStatus === STATUS.BUILD_DONE && this.options.dev) {
2017-06-11 14:17:36 +00:00
return this
}
// If building
2017-06-19 15:47:31 +00:00
/* istanbul ignore if */
2017-06-11 14:17:36 +00:00
if (this._buildStatus === STATUS.BUILDING) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(this.build())
2017-06-13 22:09:03 +00:00
}, 1000)
2017-06-11 14:17:36 +00:00
})
}
this._buildStatus = STATUS.BUILDING
2017-06-13 17:58:04 +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
2017-08-17 18:02:22 +00:00
// Babel options
this.babelOptions = _.defaults(this.options.build.babel, {
babelrc: false,
cacheDirectory: !!this.options.dev
})
if (!this.babelOptions.babelrc && !this.babelOptions.presets) {
this.babelOptions.presets = [
[require.resolve('babel-preset-vue-app'), {
targets: { ie: 9, uglify: true }
}]
]
}
2017-08-17 18:02:22 +00:00
// Map postcss plugins into instances on object mode once
if (isPureObject(this.options.build.postcss)) {
if (isPureObject(this.options.build.postcss.plugins)) {
this.options.build.postcss.plugins = Object.keys(this.options.build.postcss.plugins)
.map(p => {
const plugin = require(this.nuxt.resolvePath(p))
2017-08-17 18:02:22 +00:00
const opts = this.options.build.postcss.plugins[p]
if (opts === false) return // Disabled
const instance = plugin(opts)
return instance
}).filter(e => e)
}
}
2017-06-11 14:17:36 +00:00
// Check if pages dir exists and warn if not
this._nuxtPages = typeof this.options.build.createRoutes !== 'function'
if (this._nuxtPages) {
if (!fs.existsSync(join(this.options.srcDir, 'pages'))) {
2017-06-13 20:14:51 +00:00
let dir = this.options.srcDir
2017-06-11 14:17:36 +00:00
if (fs.existsSync(join(this.options.srcDir, '..', 'pages'))) {
2017-06-13 22:09:03 +00:00
throw new Error(`No \`pages\` directory found in ${dir}. Did you mean to run \`nuxt\` in the parent (\`../\`) directory?`)
2017-06-11 14:17:36 +00:00
} else {
2017-06-13 22:09:03 +00:00
throw new Error(`Couldn't find a \`pages\` directory in ${dir}. Please create one under the project root`)
2017-06-11 14:17:36 +00:00
}
}
}
2017-06-13 17:58:04 +00:00
2017-06-11 14:17:36 +00:00
debug(`App root: ${this.options.srcDir}`)
debug(`Generating ${this.options.buildDir} files...`)
// Create .nuxt/, .nuxt/components and .nuxt/dist folders
await remove(r(this.options.buildDir))
await mkdirp(r(this.options.buildDir, 'components'))
if (!this.options.dev) {
await mkdirp(r(this.options.buildDir, 'dist'))
}
2017-06-11 14:17:36 +00:00
// Generate routes and interpret the template files
await this.generateRoutesAndFiles()
// Start webpack build
await this.webpackBuild()
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
}
2017-10-30 17:41:22 +00:00
async generateRoutesAndFiles() {
2017-06-11 14:17:36 +00:00
debug('Generating files...')
// -- Templates --
let templatesFiles = [
'App.js',
2017-06-11 14:17:36 +00:00
'client.js',
'index.js',
'middleware.js',
'router.js',
'server.js',
'utils.js',
2017-07-10 22:53:06 +00:00
'empty.js',
2017-06-11 14:17:36 +00:00
'components/nuxt-error.vue',
'components/nuxt-loading.vue',
'components/nuxt-child.js',
'components/nuxt-link.js',
'components/nuxt.js',
2017-08-24 10:38:46 +00:00
'components/no-ssr.js',
2017-06-16 12:42:45 +00:00
'views/app.template.html',
'views/error.html'
2017-06-11 14:17:36 +00:00
]
const templateVars = {
options: this.options,
2017-09-01 16:30:49 +00:00
messages: this.options.messages,
2017-06-11 14:17:36 +00:00
uniqBy: _.uniqBy,
isDev: this.options.dev,
debug: this.options.debug,
2017-08-20 13:13:42 +00:00
mode: this.options.mode,
2017-06-13 17:58:04 +00:00
router: this.options.router,
2017-06-11 14:17:36 +00:00
env: this.options.env,
head: this.options.head,
middleware: fs.existsSync(join(this.options.srcDir, 'middleware')),
store: this.options.store,
2017-06-11 14:17:36 +00:00
css: this.options.css,
2017-07-10 22:53:06 +00:00
plugins: this.plugins,
appPath: './App.js',
2017-06-11 14:17:36 +00:00
layouts: Object.assign({}, this.options.layouts),
loading: typeof this.options.loading === 'string' ? this.relativeToBuild(this.options.srcDir, this.options.loading) : this.options.loading,
2017-06-11 14:17:36 +00:00
transition: this.options.transition,
2017-09-08 10:42:00 +00:00
layoutTransition: this.options.layoutTransition,
2017-06-11 14:17:36 +00:00
components: {
ErrorPage: this.options.ErrorPage ? this.relativeToBuild(this.options.ErrorPage) : null
2017-06-11 14:17:36 +00:00
}
}
// -- Layouts --
if (fs.existsSync(resolve(this.options.srcDir, 'layouts'))) {
2017-10-15 19:31:01 +00:00
const layoutsFiles = await glob('layouts/**/*.vue', { cwd: this.options.srcDir })
2017-08-14 12:15:00 +00:00
let hasErrorLayout = false
2017-06-11 14:17:36 +00:00
layoutsFiles.forEach((file) => {
2017-10-15 19:31:01 +00:00
let name = file.split('/').slice(1).join('/').replace(/\.vue$/, '')
2017-08-14 12:15:00 +00:00
if (name === 'error') {
hasErrorLayout = true
return
}
templateVars.layouts[name] = this.relativeToBuild(this.options.srcDir, file)
2017-06-11 14:17:36 +00:00
})
2017-08-14 12:15:00 +00:00
if (!templateVars.components.ErrorPage && hasErrorLayout) {
2017-08-17 13:13:56 +00:00
templateVars.components.ErrorPage = this.relativeToBuild(this.options.srcDir, 'layouts/error.vue')
2017-06-11 14:17:36 +00:00
}
}
// If no default layout, create its folder and add the default folder
if (!templateVars.layouts.default) {
await mkdirp(r(this.options.buildDir, 'layouts'))
templatesFiles.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
}
// -- Routes --
debug('Generating routes...')
// If user defined a custom method to create routes
if (this._nuxtPages) {
// Use nuxt.js createRoutes bases on pages/
2017-08-17 13:13:56 +00:00
const files = await glob('pages/**/*.vue', { cwd: this.options.srcDir })
templateVars.router.routes = createRoutes(files, this.options.srcDir)
2017-06-11 14:17:36 +00:00
} else {
templateVars.router.routes = this.options.build.createRoutes(this.options.srcDir)
}
2017-07-03 11:11:40 +00:00
2017-10-30 21:39:08 +00:00
await this.nuxt.callHook('build:extendRoutes', templateVars.router.routes, r)
2017-07-03 11:11:40 +00:00
2017-06-11 14:17:36 +00:00
// router.extendRoutes method
if (typeof this.options.router.extendRoutes === 'function') {
// let the user extend the routes
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
2017-06-11 14:17:36 +00:00
// -- Store --
// Add store if needed
if (this.options.store) {
templatesFiles.push('store.js')
}
// Resolve template files
const customTemplateFiles = this.options.build.templates.map(t => t.dst || basename(t.src || t))
templatesFiles = templatesFiles.map(file => {
// Skip if custom file was already provided in build.templates[]
if (customTemplateFiles.indexOf(file) !== -1) {
return
}
// Allow override templates using a file with same name in ${srcDir}/app
const customPath = r(this.options.srcDir, 'app', file)
const customFileExists = fs.existsSync(customPath)
return {
2017-06-16 12:42:45 +00:00
src: customFileExists
? customPath
2017-06-16 13:04:42 +00:00
: r(this.options.nuxtAppDir, file),
2017-06-11 14:17:36 +00:00
dst: file,
custom: customFileExists
}
}).filter(i => !!i)
// -- Custom templates --
// Add custom template files
templatesFiles = templatesFiles.concat(this.options.build.templates.map(t => {
return Object.assign({
src: r(this.options.srcDir, t.src || t),
dst: t.dst || basename(t.src || t),
custom: true
}, t)
}))
2017-08-18 10:26:19 +00:00
// -- Loading indicator --
if (this.options.loadingIndicator.name) {
const indicatorPath1 = resolve(this.options.nuxtAppDir, 'views/loading', this.options.loadingIndicator.name + '.html')
const indicatorPath2 = this.nuxt.resolvePath(this.options.loadingIndicator.name)
const indicatorPath = existsSync(indicatorPath1) ? indicatorPath1 : (existsSync(indicatorPath2) ? indicatorPath2 : null)
if (indicatorPath) {
templatesFiles.push({
src: indicatorPath,
dst: 'loading.html',
options: this.options.loadingIndicator
})
2017-08-18 12:23:10 +00:00
} else {
console.error(`Could not fetch loading indicator: ${this.options.loadingIndicator.name}`) // eslint-disable-line no-console
2017-08-18 10:26:19 +00:00
}
}
2017-10-30 21:39:08 +00:00
await this.nuxt.callHook('build:templates', { templatesFiles, templateVars, resolve: r })
2017-07-03 11:11:40 +00:00
2017-06-11 14:17:36 +00:00
// Interpret and move template files to .nuxt/
2017-06-15 22:19:53 +00:00
await Promise.all(templatesFiles.map(async ({ src, dst, options, custom }) => {
2017-06-11 14:17:36 +00:00
// Add template to watchers
this.options.build.watch.push(src)
// Render template to dst
const fileContent = await readFile(src, 'utf8')
let content
try {
const template = _.template(fileContent, {
imports: {
serialize,
hash,
r,
wp,
wChunk,
resolvePath: this.nuxt.resolvePath.bind(this.nuxt),
relativeToBuild: this.relativeToBuild
}
})
content = template(Object.assign({}, templateVars, {
options: options || {},
custom,
src,
dst
}))
} catch (err) {
throw new Error(`Could not compile template ${src}: ${err.message}`)
}
2017-06-11 14:17:36 +00:00
const path = r(this.options.buildDir, dst)
// Ensure parent dir exits
await mkdirp(dirname(path))
// Write file
await writeFile(path, content, 'utf8')
}))
}
2017-10-30 17:41:22 +00:00
async webpackBuild() {
debug('Building files...')
2017-07-10 22:53:06 +00:00
const compilersOptions = []
// Client
2017-07-10 22:53:06 +00:00
const clientConfig = clientWebpackConfig.call(this)
compilersOptions.push(clientConfig)
// Server
let serverConfig = null
2017-07-11 00:24:39 +00:00
if (this.options.build.ssr) {
serverConfig = serverWebpackConfig.call(this)
2017-07-11 00:24:39 +00:00
compilersOptions.push(serverConfig)
}
2017-07-10 22:53:06 +00:00
// Alias plugins to their real path
this.plugins.forEach(p => {
const src = this.relativeToBuild(p.src)
// Client config
if (!clientConfig.resolve.alias[p.name]) {
clientConfig.resolve.alias[p.name] = src
}
// Server config
if (serverConfig && !serverConfig.resolve.alias[p.name]) {
2017-07-10 22:53:06 +00:00
// Alias to noop for ssr:false plugins
serverConfig.resolve.alias[p.name] = p.ssr ? src : './empty.js'
}
})
// Make a dll plugin after compile to make nuxt dev builds faster
if (this.options.build.dll && this.options.dev) {
compilersOptions.push(dllWebpackConfig.call(this, clientConfig))
}
// Initialize shared FS and Cache
const sharedFS = this.options.dev && new MFS()
const sharedCache = {}
// Initialize compilers
2017-11-07 09:46:29 +00:00
this.compilers = compilersOptions.map(compilersOption => {
const compiler = webpack(compilersOption)
// In dev, write files in memory FS (except for DLL)
if (sharedFS && !compiler.name.includes('-dll')) {
compiler.outputFileSystem = sharedFS
}
compiler.cache = sharedCache
2017-11-07 09:46:29 +00:00
return compiler
})
2017-06-15 22:19:53 +00:00
// Start Builds
await sequence(this.compilers, (compiler) => new Promise(async (resolve, reject) => {
const name = compiler.options.name
2017-10-30 21:39:08 +00:00
await this.nuxt.callHook('build:compile', { name, compiler })
// Resolve only when compiler emit done event
compiler.plugin('done', async (stats) => {
2017-10-30 21:39:08 +00:00
await this.nuxt.callHook('build:compiled', { name, compiler, stats })
2017-10-31 17:33:25 +00:00
// Reload renderer if available
this.nuxt.renderer.loadResources(sharedFS || fs)
// Resolve on next tick
process.nextTick(resolve)
})
// --- Dev Build ---
2017-06-15 14:53:00 +00:00
if (this.options.dev) {
// Client Build, watch is started by dev-middleware
2017-06-15 22:19:53 +00:00
if (compiler.options.name === 'client') {
return this.webpackDev(compiler)
}
// DLL build, should run only once
if (compiler.options.name.includes('-dll')) {
compiler.run((err, stats) => {
if (err) return reject(err)
debug('[DLL] updated')
2017-06-18 11:50:43 +00:00
})
return
2017-06-15 22:19:53 +00:00
}
// Server, build and watch for changes
compiler.watch(this.options.watchers.webpack, (err) => {
2017-06-20 13:12:33 +00:00
/* istanbul ignore if */
if (err) return reject(err)
2017-06-18 11:50:43 +00:00
})
return
2017-06-15 14:53:00 +00:00
}
// --- Production Build ---
compiler.run((err, stats) => {
/* istanbul ignore if */
if (err) {
console.error(err) // eslint-disable-line no-console
return reject(err)
}
2017-07-03 11:28:10 +00:00
// Show build stats for production
console.log(stats.toString(this.webpackStats)) // eslint-disable-line no-console
/* istanbul ignore if */
if (stats.hasErrors()) {
return reject(new Error('Webpack build exited with errors'))
}
})
}))
2017-06-11 14:17:36 +00:00
}
2017-10-30 17:41:22 +00:00
webpackDev(compiler) {
2017-06-15 22:19:53 +00:00
debug('Adding webpack middleware...')
// Create webpack dev middleware
this.webpackDevMiddleware = pify(webpackDevMiddleware(compiler, Object.assign({
2017-06-15 14:53:00 +00:00
publicPath: this.options.build.publicPath,
2017-06-11 14:17:36 +00:00
stats: this.webpackStats,
noInfo: true,
2017-06-15 22:19:53 +00:00
quiet: true,
2017-06-11 14:17:36 +00:00
watchOptions: this.options.watchers.webpack
}, this.options.build.devMiddleware)))
this.webpackHotMiddleware = pify(webpackHotMiddleware(compiler, Object.assign({
log: false,
2017-09-11 20:35:09 +00:00
heartbeat: 10000
}, this.options.build.hotMiddleware)))
2017-06-11 14:17:36 +00:00
// Inject to renderer instance
if (this.nuxt.renderer) {
this.nuxt.renderer.webpackDevMiddleware = this.webpackDevMiddleware
this.nuxt.renderer.webpackHotMiddleware = this.webpackHotMiddleware
}
2017-06-15 22:19:53 +00:00
// Stop webpack middleware on nuxt.close()
2017-10-30 21:39:08 +00:00
this.nuxt.hook('close', () => new Promise(resolve => {
2017-06-15 22:19:53 +00:00
this.webpackDevMiddleware.close(() => resolve())
}))
// Start watching files
this.watchFiles()
2017-06-11 14:17:36 +00:00
}
2017-10-30 17:41:22 +00:00
watchFiles() {
2017-06-11 14:17:36 +00:00
const patterns = [
r(this.options.srcDir, 'layouts'),
r(this.options.srcDir, 'store'),
r(this.options.srcDir, 'middleware'),
2017-08-17 13:13:56 +00:00
r(this.options.srcDir, 'layouts/*.vue'),
r(this.options.srcDir, 'layouts/**/*.vue')
2017-06-11 14:17:36 +00:00
]
if (this._nuxtPages) {
patterns.push(r(this.options.srcDir, 'pages'))
2017-08-17 13:13:56 +00:00
patterns.push(r(this.options.srcDir, 'pages/*.vue'))
patterns.push(r(this.options.srcDir, 'pages/**/*.vue'))
2017-06-11 14:17:36 +00:00
}
const options = Object.assign({}, this.options.watchers.chokidar, {
ignoreInitial: true
})
/* istanbul ignore next */
const refreshFiles = _.debounce(() => this.generateRoutesAndFiles(), 200)
2017-06-15 22:19:53 +00:00
// Watch for src Files
let filesWatcher = chokidar.watch(patterns, options)
2017-06-11 14:17:36 +00:00
.on('add', refreshFiles)
.on('unlink', refreshFiles)
2017-06-15 22:19:53 +00:00
2017-06-11 14:17:36 +00:00
// Watch for custom provided files
2017-06-15 22:19:53 +00:00
let customFilesWatcher = chokidar.watch(_.uniq(this.options.build.watch), options)
2017-06-11 14:17:36 +00:00
.on('change', refreshFiles)
2017-06-15 22:19:53 +00:00
// Stop watching on nuxt.close()
2017-10-30 21:39:08 +00:00
this.nuxt.hook('close', () => {
2017-06-15 22:19:53 +00:00
filesWatcher.close()
customFilesWatcher.close()
})
2017-06-11 14:17:36 +00:00
}
}
const STATUS = {
INITIAL: 1,
BUILD_DONE: 2,
BUILDING: 3
}