Nuxt/lib/builder.js

427 lines
13 KiB
JavaScript
Raw Normal View History

2017-06-11 14:17:36 +00:00
import _ from 'lodash'
import chokidar from 'chokidar'
import fs from 'fs-extra'
import hash from 'hash-sum'
import pify from 'pify'
import webpack from 'webpack'
import serialize from 'serialize-javascript'
import { join, resolve, basename, dirname } from 'path'
2017-06-13 17:58:04 +00:00
import Tapable from 'tappable'
2017-06-15 22:19:53 +00:00
import MFS from 'memory-fs'
2017-06-15 22:28:08 +00:00
import { r, wp, createRoutes, parallel } from './utils'
2017-06-11 14:17:36 +00:00
import clientWebpackConfig from './webpack/client.config.js'
import serverWebpackConfig from './webpack/server.config.js'
const debug = require('debug')('nuxt:build')
debug.color = 2 // Force green color
const remove = pify(fs.remove)
const readFile = pify(fs.readFile)
const utimes = pify(fs.utimes)
const writeFile = pify(fs.writeFile)
const mkdirp = pify(fs.mkdirp)
const glob = pify(require('glob'))
export default class Builder extends Tapable {
constructor (nuxt) {
super()
this.nuxt = nuxt
this.options = nuxt.options
this._buildStatus = STATUS.INITIAL
// Fields that set on build
this.compiler = null
this.webpackDevMiddleware = null
this.webpackHotMiddleware = null
2017-06-11 14:17:36 +00:00
// Add extra loaders only if they are not already provided
let extraDefaults = {}
if (this.options.build && !Array.isArray(this.options.build.loaders)) {
extraDefaults.loaders = defaultsLoaders
}
if (this.options.build && !Array.isArray(this.options.build.postcss)) {
extraDefaults.postcss = defaultsPostcss
}
_.defaultsDeep(this.options.build, extraDefaults)
// 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,
colors: true
}
}
async build () {
// Avoid calling this method multiple times
if (this._buildStatus === STATUS.BUILD_DONE) {
return this
}
// If building
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
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
return this
}
async generateRoutesAndFiles () {
debug('Generating files...')
// -- Templates --
let templatesFiles = [
'App.vue',
'client.js',
'index.js',
'middleware.js',
'router.js',
'server.js',
'utils.js',
'components/nuxt-error.vue',
'components/nuxt-loading.vue',
'components/nuxt-child.js',
'components/nuxt-link.js',
'components/nuxt.vue'
]
const templateVars = {
options: this.options,
uniqBy: _.uniqBy,
isDev: this.options.dev,
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,
plugins: this.options.plugins.map((p, i) => {
if (typeof p === 'string') p = { src: p }
p.src = r(this.options.srcDir, p.src)
return { src: p.src, ssr: (p.ssr !== false), name: `plugin${i}` }
}),
appPath: './App.vue',
layouts: Object.assign({}, this.options.layouts),
loading: typeof this.options.loading === 'string' ? r(this.options.srcDir, this.options.loading) : this.options.loading,
2017-06-11 14:17:36 +00:00
transition: this.options.transition,
components: {
ErrorPage: this.options.ErrorPage ? r(this.options.ErrorPage) : null
}
}
// -- Layouts --
if (fs.existsSync(resolve(this.options.srcDir, 'layouts'))) {
const layoutsFiles = await glob('layouts/*.vue', { cwd: this.options.srcDir })
layoutsFiles.forEach((file) => {
let name = file.split('/').slice(-1)[0].replace('.vue', '')
if (name === 'error') return
templateVars.layouts[name] = r(this.options.srcDir, file)
})
if (layoutsFiles.includes('layouts/error.vue')) {
templateVars.components.ErrorPage = r(this.options.srcDir, 'layouts/error.vue')
}
}
// 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')
templateVars.layouts.default = r(__dirname, 'app', 'layouts', 'default.vue')
}
// -- Routes --
debug('Generating routes...')
// If user defined a custom method to create routes
if (this._nuxtPages) {
// Use nuxt.js createRoutes bases on pages/
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)
}
// router.extendRoutes method
if (typeof this.options.router.extendRoutes === 'function') {
// let the user extend the routes
2017-06-13 17:58:04 +00:00
this.options.router.extendRoutes(templateVars.router.routes, r)
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 {
src: customFileExists ? customPath : r(__dirname, 'app', file),
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)
}))
// 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')
const template = _.template(fileContent, {
imports: {
serialize,
hash,
r,
wp
}
})
const content = template(Object.assign({}, templateVars, {
options: options || {},
custom,
src,
dst
}))
const path = r(this.options.buildDir, dst)
// Ensure parent dir exits
await mkdirp(dirname(path))
// Write file
await writeFile(path, content, 'utf8')
// Fix webpack loop (https://github.com/webpack/watchpack/issues/25#issuecomment-287789288)
2017-06-15 22:19:53 +00:00
const dateFS = Date.now() / 1000 - 1000
2017-06-11 14:17:36 +00:00
return utimes(path, dateFS, dateFS)
}))
}
webpackBuild () {
debug('Building files...')
let compilersOptions = []
// Client
let clientConfig = clientWebpackConfig.call(this)
compilersOptions.push(clientConfig)
// Server
2017-06-14 16:58:14 +00:00
let serverConfig = serverWebpackConfig.call(this)
compilersOptions.push(serverConfig)
2017-06-15 22:19:53 +00:00
// Simulate webpack multi compiler interface
// Separate compilers are simpler, safer and faster
this.compiler = { cache: {}, compilers: [] }
compilersOptions.forEach(compilersOption => {
this.compiler.compilers.push(webpack(compilersOption))
})
this.compiler.plugin = (...args) => {
this.compiler.compilers.forEach(compiler => {
compiler.plugin(...args)
})
}
// Access to compilers with name
this.compiler.compilers.forEach(compiler => {
if (compiler.name) {
this.compiler[compiler.name] = compiler
}
})
2017-06-15 22:19:53 +00:00
// Add dev Stuff
2017-06-11 14:17:36 +00:00
if (this.options.dev) {
this.webpackDev()
2017-06-11 14:17:36 +00:00
}
2017-06-15 22:19:53 +00:00
// Start Builds
return parallel(this.compiler.compilers, compiler => new Promise((resolve, reject) => {
let _resolved = false
const handler = (err, stats) => {
if (_resolved) return
_resolved = true
if (err) {
return reject(err)
2017-06-11 14:17:36 +00:00
}
2017-06-15 22:19:53 +00:00
if (!this.options.dev) {
// Show build stats for production
2017-06-15 22:28:08 +00:00
console.log(stats.toString(this.webpackStats)) // eslint-disable-line no-console
2017-06-15 22:19:53 +00:00
if (stats.hasErrors()) {
return reject(new Error('Webpack build exited with errors'))
2017-06-11 14:17:36 +00:00
}
}
resolve()
2017-06-15 14:53:00 +00:00
}
if (this.options.dev) {
2017-06-15 22:19:53 +00:00
if (compiler.options.name === 'client') {
// Client watch is started by dev-middleware
resolve()
} else {
// Build and watch for changes
compiler.watch(this.options.watchers.webpack, handler)
}
2017-06-15 14:53:00 +00:00
} else {
2017-06-15 22:19:53 +00:00
// Production build
compiler.run(handler)
2017-06-15 14:53:00 +00:00
}
2017-06-15 22:19:53 +00:00
}))
2017-06-11 14:17:36 +00:00
}
webpackDev () {
2017-06-15 22:19:53 +00:00
// Use shared MFS + Cache for faster builds
let mfs = new MFS()
this.compiler.compilers.forEach(compiler => {
compiler.outputFileSystem = mfs
2017-06-15 22:19:53 +00:00
compiler.cache = this.compiler.cache
2017-06-11 14:17:36 +00:00
})
2017-06-15 22:19:53 +00:00
// Run after each compile
this.compiler.plugin('done', stats => {
2017-06-15 22:28:08 +00:00
console.log(stats.toString(this.webpackStats)) // eslint-disable-line no-console
2017-06-15 14:53:00 +00:00
// Reload renderer if available
if (this.nuxt.renderer) {
this.nuxt.renderer.loadResources(mfs)
}
})
2017-06-15 22:19:53 +00:00
// Add dev Middleware
debug('Adding webpack middleware...')
// Create webpack dev middleware
this.webpackDevMiddleware = pify(require('webpack-dev-middleware')(this.compiler.client, {
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
}))
2017-06-15 22:19:53 +00:00
this.webpackHotMiddleware = pify(require('webpack-hot-middleware')(this.compiler.client, {
log: false,
heartbeat: 2500
2017-06-11 14:17:36 +00:00
}))
2017-06-15 22:19:53 +00:00
// Stop webpack middleware on nuxt.close()
this.nuxt.plugin('close', () => new Promise(resolve => {
this.webpackDevMiddleware.close(() => resolve())
}))
// Start watching files
this.watchFiles()
2017-06-11 14:17:36 +00:00
}
watchFiles () {
const patterns = [
r(this.options.srcDir, 'layouts'),
r(this.options.srcDir, 'store'),
r(this.options.srcDir, 'middleware'),
r(this.options.srcDir, 'layouts/*.vue'),
r(this.options.srcDir, 'layouts/**/*.vue')
]
if (this._nuxtPages) {
patterns.push(r(this.options.srcDir, 'pages'))
patterns.push(r(this.options.srcDir, 'pages/*.vue'))
patterns.push(r(this.options.srcDir, 'pages/**/*.vue'))
}
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()
this.nuxt.plugin('close', () => {
filesWatcher.close()
customFilesWatcher.close()
})
2017-06-11 14:17:36 +00:00
}
}
const defaultsLoaders = [
{
test: /\.(png|jpe?g|gif|svg)$/,
loader: 'url-loader',
query: {
limit: 1000, // 1KO
name: 'img/[name].[hash:7].[ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 1000, // 1 KO
name: 'fonts/[name].[hash:7].[ext]'
}
}
]
const defaultsPostcss = [
require('autoprefixer')({
browsers: ['last 3 versions']
})
]
const STATUS = {
INITIAL: 1,
BUILD_DONE: 2,
BUILDING: 3
}