Nuxt/lib/build/index.js

330 lines
10 KiB
JavaScript
Raw Normal View History

2016-11-07 01:34:58 +00:00
'use strict'
const debug = require('debug')('nuxt:build')
const _ = require('lodash')
const co = require('co')
const chokidar = require('chokidar')
2016-11-11 14:30:11 +00:00
const fs = require('fs-extra')
2016-11-07 01:34:58 +00:00
const hash = require('hash-sum')
const pify = require('pify')
const webpack = require('webpack')
const { createBundleRenderer } = require('vue-server-renderer')
2016-11-20 11:23:48 +00:00
const { join, resolve, sep, posix } = require('path')
const basename = posix.basename
2016-11-11 14:30:11 +00:00
const remove = pify(fs.remove)
const readFile = pify(fs.readFile)
const writeFile = pify(fs.writeFile)
const mkdirp = pify(fs.mkdirp)
2016-11-24 00:47:11 +00:00
const glob = pify(require('glob'))
2016-11-20 10:37:53 +00:00
const reqSep = /\//g
const sysSep = _.escapeRegExp(sep)
const normalize = string => string.replace(reqSep, sysSep)
const wp = function (p) {
if (/^win/.test(process.platform)) {
p = p.replace(/\\/g, '\\\\')
}
return p
}
2016-11-16 17:06:54 +00:00
const r = function () {
2016-11-20 10:37:53 +00:00
let args = Array.from(arguments)
2016-11-16 17:06:54 +00:00
if (_.last(args).includes('~')) {
2016-11-20 10:37:53 +00:00
return wp(_.last(args))
2016-11-16 17:06:54 +00:00
}
args = args.map(normalize)
2016-11-20 10:37:53 +00:00
return wp(resolve.apply(null, args))
2016-11-16 17:06:54 +00:00
}
2016-11-07 01:34:58 +00:00
const defaults = {
filenames: {
css: 'style.css',
vendor: 'vendor.bundle.js',
app: 'nuxt.bundle.js'
},
vendor: [],
loaders: [],
2016-11-18 09:38:47 +00:00
plugins: [],
2016-11-22 23:47:31 +00:00
babel: {},
postcss: []
}
const defaultsLoaders = [
{
test: /\.(png|jpe?g|gif|svg)$/,
2016-11-14 22:59:54 +00:00
loader: 'url-loader',
2016-11-10 18:34:59 +00:00
query: {
limit: 1000, // 1KO
name: 'img/[name].[ext]?[hash]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
2016-11-14 22:59:54 +00:00
loader: 'url-loader',
query: {
limit: 1000, // 1 KO
name: 'fonts/[name].[hash:7].[ext]'
}
}
]
2016-11-22 23:47:31 +00:00
const defaultsPostcss = [
require('autoprefixer')({
browsers: ['last 3 versions']
})
]
2016-11-07 01:34:58 +00:00
module.exports = function * () {
// Defaults build options
2016-11-22 23:47:31 +00:00
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
this.options.build = _.defaultsDeep(this.options.build, defaults, extraDefaults)
2016-11-10 18:34:59 +00:00
if (!this.options._build && !this.options._renderer) {
return Promise.resolve()
}
if (!this.options._build) {
const serverConfig = getWebpackServerConfig.call(this)
const bundlePath = join(serverConfig.output.path, serverConfig.output.filename)
2016-11-10 01:19:47 +00:00
if (!fs.existsSync(bundlePath)) {
console.error('> No build files found, please run `nuxt build` before launching `nuxt start`')
process.exit(1)
}
2016-11-11 14:30:11 +00:00
const bundle = yield readFile(bundlePath, 'utf8')
createRenderer.call(this, bundle)
return Promise.resolve()
}
2016-11-07 01:34:58 +00:00
/*
** Check if pages dir exists and warn if not
*/
if (!fs.existsSync(join(this.dir, 'pages'))) {
if (fs.existsSync(join(this.dir, '..', 'pages'))) {
console.error('> No `pages` directory found. Did you mean to run `nuxt` in the parent (`../`) directory?')
2016-11-07 01:34:58 +00:00
} else {
console.error('> Couldn\'t find a `pages` directory. Please create one under the project root')
}
2016-11-10 01:19:47 +00:00
process.exit(1)
2016-11-07 01:34:58 +00:00
}
debug(`App root: ${this.dir}`)
debug('Generating .nuxt/ files...')
/*
** Create .nuxt/, .nuxt/components and .nuxt/dist folders
*/
2016-11-11 14:30:11 +00:00
yield remove(r(this.dir, '.nuxt'))
2016-11-07 01:34:58 +00:00
yield mkdirp(r(this.dir, '.nuxt/components'))
if (!this.dev) {
2016-11-07 01:34:58 +00:00
yield mkdirp(r(this.dir, '.nuxt/dist'))
}
// Resolve custom routes component path
2016-11-10 16:16:37 +00:00
this.options.router.routes.forEach((route) => {
if (route.component.slice(-4) !== '.vue') {
route.component = route.component + '.vue'
}
2016-11-16 17:06:54 +00:00
route.component = r(this.dir, route.component)
})
// Generate routes and interpret the template files
yield generateRoutesAndFiles.call(this)
/*
** Generate .nuxt/dist/ files
*/
if (this.dev) {
debug('Adding webpack middlewares...')
createWebpackMiddlewares.call(this)
webpackWatchAndUpdate.call(this)
watchPages.call(this)
} else {
debug('Building files...')
yield [
webpackRunClient.call(this),
webpackRunServer.call(this)
]
}
}
function * generateRoutesAndFiles () {
debug('Generating routes...')
2016-11-07 01:34:58 +00:00
/*
** Generate routes based on files
*/
const files = yield glob('pages/**/*.vue', { cwd: this.dir })
let routes = []
files.forEach((file) => {
let path = file.replace(/^pages/, '').replace(/index\.vue$/, '/').replace(/\.vue$/, '').replace(/\/{2,}/g, '/')
2016-12-03 14:12:05 +00:00
let name = file.replace(/^pages/, '').replace(/\.vue$/, '').replace(/\/{2,}/g, '/').split('/').slice(1).join('-')
2016-11-20 11:23:48 +00:00
if (basename(path)[0] === '_') return
2016-12-03 14:12:05 +00:00
routes.push({ path: path, component: r(this.dir, file), name: name })
2016-11-07 01:34:58 +00:00
})
// Concat pages routes and custom routes in this.routes
2016-11-10 16:16:37 +00:00
this.routes = routes.concat(this.options.router.routes)
2016-11-07 01:34:58 +00:00
/*
** Interpret and move template files to .nuxt/
*/
debug('Generating files...')
2016-11-07 01:34:58 +00:00
let templatesFiles = [
'App.vue',
'client.js',
'index.js',
'router.js',
'server.js',
'utils.js',
'components/nuxt-container.vue',
'components/nuxt.vue',
2016-11-10 20:52:27 +00:00
'components/nuxt-loading.vue'
2016-11-07 01:34:58 +00:00
]
let templateVars = {
2016-11-20 11:23:48 +00:00
uniqBy: _.uniqBy,
isDev: this.dev,
2016-11-10 16:16:37 +00:00
router: {
base: this.options.router.base,
2016-11-24 00:47:11 +00:00
linkActiveClass: this.options.router.linkActiveClass
2016-11-10 16:16:37 +00:00
},
2016-12-04 18:15:11 +00:00
env: this.options.env,
2016-11-14 22:59:54 +00:00
head: this.options.head,
2016-11-07 01:34:58 +00:00
store: this.options.store,
css: this.options.css,
2016-11-08 01:57:55 +00:00
plugins: this.options.plugins.map((p) => r(this.dir, p)),
appPath: './App.vue',
2016-11-11 14:30:11 +00:00
loading: (typeof this.options.loading === 'string' ? r(this.dir, this.options.loading) : this.options.loading),
transition: this.options.transition,
2016-11-07 01:34:58 +00:00
components: {
2016-11-10 20:52:27 +00:00
Loading: r(__dirname, '..', 'app', 'components', 'nuxt-loading.vue'),
2016-11-25 16:56:46 +00:00
ErrorPage: r(__dirname, '..', 'app', 'components', 'nuxt-error.vue')
2016-11-10 16:16:37 +00:00
}
2016-11-07 01:34:58 +00:00
}
2016-11-11 14:30:11 +00:00
if (templateVars.loading === 'string' && templateVars.loading.slice(-4) !== '.vue') {
templateVars.loading = templateVars.loading + '.vue'
}
// Format routes for the lib/app/router.js template
2016-11-24 00:47:11 +00:00
templateVars.router.routes = this.routes.map((route) => {
const r = Object.assign({}, route)
r._component = r.component
r._name = '_' + hash(r._component)
r.component = r._name
r.path = r.path.replace(/\\/g, '\\\\') // regex expression in route path escaping for lodash templating
return r
})
if (files.includes('pages/_app.vue')) {
templateVars.appPath = r(this.dir, 'pages/_app.vue')
}
2016-11-25 16:56:46 +00:00
if (files.includes('pages/_error.vue')) {
2016-11-07 01:34:58 +00:00
templateVars.components.ErrorPage = r(this.dir, 'pages/_error.vue')
}
let moveTemplates = templatesFiles.map((file) => {
return readFile(r(__dirname, '..', 'app', file), 'utf8')
.then((fileContent) => {
const template = _.template(fileContent)
const content = template(templateVars)
return writeFile(r(this.dir, '.nuxt', file), content, 'utf8')
})
})
yield moveTemplates
}
function getWebpackClientConfig () {
const clientConfigPath = r(__dirname, 'webpack', 'client.config.js')
return require(clientConfigPath).call(this)
2016-11-07 01:34:58 +00:00
}
function getWebpackServerConfig () {
const configServerPath = r(__dirname, 'webpack', 'server.config.js')
return require(configServerPath).call(this)
2016-11-07 01:34:58 +00:00
}
function createWebpackMiddlewares () {
const clientConfig = getWebpackClientConfig.call(this)
// setup on the fly compilation + hot-reload
clientConfig.entry.app = ['webpack-hot-middleware/client?reload=true', clientConfig.entry.app]
2016-11-07 01:34:58 +00:00
clientConfig.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
)
const clientCompiler = webpack(clientConfig)
// Add the middlewares to the instance context
this.webpackDevMiddleware = pify(require('webpack-dev-middleware')(clientCompiler, {
publicPath: clientConfig.output.publicPath,
stats: {
colors: true,
chunks: false
},
quiet: false,
2016-11-07 01:34:58 +00:00
noInfo: true
}))
this.webpackHotMiddleware = pify(require('webpack-hot-middleware')(clientCompiler))
}
function webpackWatchAndUpdate () {
const MFS = require('memory-fs') // <- dependencies of webpack
const mfs = new MFS()
const serverConfig = getWebpackServerConfig.call(this)
const serverCompiler = webpack(serverConfig)
const outputPath = join(serverConfig.output.path, serverConfig.output.filename)
serverCompiler.outputFileSystem = mfs
this.webpackServerWatcher = serverCompiler.watch({}, (err, stats) => {
if (err) throw err
stats = stats.toJson()
stats.errors.forEach(err => console.error(err))
stats.warnings.forEach(err => console.warn(err))
createRenderer.call(this, mfs.readFileSync(outputPath, 'utf-8'))
})
}
function webpackRunClient () {
return new Promise((resolve, reject) => {
const clientConfig = getWebpackClientConfig.call(this)
const serverCompiler = webpack(clientConfig)
serverCompiler.run((err, stats) => {
if (err) return reject(err)
console.log('[nuxt:build:client]\n', stats.toString({ chunks: false, colors: true }))
2016-11-07 01:34:58 +00:00
resolve()
})
})
}
function webpackRunServer () {
return new Promise((resolve, reject) => {
const serverConfig = getWebpackServerConfig.call(this)
const serverCompiler = webpack(serverConfig)
serverCompiler.run((err, stats) => {
if (err) return reject(err)
console.log('[nuxt:build:server]\n', stats.toString({ chunks: false, colors: true }))
2016-11-07 01:34:58 +00:00
const bundlePath = join(serverConfig.output.path, serverConfig.output.filename)
2016-11-11 14:30:11 +00:00
readFile(bundlePath, 'utf8')
.then((bundle) => {
createRenderer.call(this, bundle)
resolve()
})
2016-11-07 01:34:58 +00:00
})
})
}
function createRenderer (bundle) {
// Create bundle renderer to give a fresh context for every request
let cacheConfig = false
if (this.options.cache) {
this.options.cache = (typeof this.options.cache !== 'object' ? {} : this.options.cache)
cacheConfig = require('lru-cache')(_.defaults(this.options.cache, {
max: 1000,
maxAge: 1000 * 60 * 15
}))
}
this.renderer = createBundleRenderer(bundle, {
cache: cacheConfig
})
this.renderToString = pify(this.renderer.renderToString)
this.renderToStream = this.renderer.renderToStream
}
function watchPages () {
const patterns = [ r(this.dir, 'pages/*.vue'), r(this.dir, 'pages/**/*.vue') ]
const options = {
// ignored: '**/_*.vue',
ignoreInitial: true
}
const refreshFiles = _.debounce(() => {
var d = Date.now()
co(generateRoutesAndFiles.bind(this))
.then(() => {
console.log('Time to gen:' + (Date.now() - d) + 'ms')
})
}, 200)
this.pagesFilesWatcher = chokidar.watch(patterns, options)
.on('add', refreshFiles)
.on('unlink', refreshFiles)
}