Merge pull request #3041 from nuxt/feat/esm

feat: rewrite core to es
This commit is contained in:
Sébastien Chopin 2018-03-19 16:22:59 +01:00 committed by GitHub
commit f3bb1a69d8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
144 changed files with 1028 additions and 940 deletions

View File

@ -8,20 +8,44 @@ module.exports = {
browser: true,
node: true
},
extends: ['standard', 'standard-jsx'],
extends: [
'standard',
'standard-jsx',
'plugin:import/errors',
'plugin:import/warnings'
],
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
settings: {
'import/resolver': {
node: { extensions: ['.js', '.mjs'] }
}
},
rules: {
// allow paren-less arrow functions
// Enforce import order
'import/order': 2,
// Imports should come first
'import/first': 2,
// Other import rules
"import/no-mutable-exports": 2,
// Allow unresolved imports
'import/no-unresolved': 0,
// Allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
// Allow async-await
'generator-star-spacing': 0,
// allow debugger during development
// Allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
// do not allow console.logs etc...
// Do not allow console.logs etc...
'no-console': 2,
'space-before-function-paren': [
2,
@ -31,5 +55,6 @@ module.exports = {
}
],
},
globals: {}
}

View File

@ -1,7 +1,10 @@
const { Utils } = require('../..')
const { resolve } = require('path')
const { existsSync } = require('fs')
const { Utils } = require('../..')
const { requireModule } = require('../../lib/common/module')
const getRootDir = argv => resolve(argv._[0] || '.')
const getNuxtConfigFile = argv => resolve(getRootDir(argv), argv['config-file'])
@ -15,7 +18,7 @@ exports.loadNuxtConfig = argv => {
if (existsSync(nuxtConfigFile)) {
delete require.cache[nuxtConfigFile]
options = require(nuxtConfigFile)
options = requireModule(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError('Could not load config file: ' + argv['config-file'])
}

View File

@ -3,17 +3,15 @@
const defaultsDeep = require('lodash/defaultsDeep')
const debug = require('debug')('nuxt:build')
debug.color = 2 // force green color
const parseArgs = require('minimist')
const chokidar = require('chokidar')
const { version } = require('../package.json')
const { version } = require('../package.json')
const { Nuxt, Builder, Utils } = require('..')
const {
loadNuxtConfig,
getLatestHost,
nuxtConfigFile
} = require('./common/utils')
const { loadNuxtConfig, getLatestHost, nuxtConfigFile } = require('./common/utils')
debug.color = 2 // force green color
const argv = parseArgs(process.argv.slice(2), {
alias: {

View File

@ -2,8 +2,8 @@
/* eslint-disable no-console */
const fs = require('fs')
const parseArgs = require('minimist')
const { resolve } = require('path')
const parseArgs = require('minimist')
const { Nuxt, Utils } = require('..')
const { loadNuxtConfig, getLatestHost } = require('./common/utils')

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
title: 'Nuxt Blog',
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
loading: {
color: '#4FC08D',
failedColor: '#bf5050',

View File

@ -1,4 +1,4 @@
const express = require('express')
import express from 'express'
// Create express router
const router = express.Router()
@ -30,7 +30,7 @@ router.post('/logout', (req, res) => {
})
// Export the server middleware
module.exports = {
export default {
path: '/api',
handler: router
}

View File

@ -1,7 +1,7 @@
const bodyParser = require('body-parser')
const session = require('express-session')
import bodyParser from 'body-parser'
import session from 'express-session'
module.exports = {
export default {
head: {
title: 'Auth Routes',
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
render: {
bundleRenderer: {
cache: require('lru-cache')({

View File

@ -1,4 +1,4 @@
module.exports = function () {
export default function () {
// Add .coffee extension for store, middleware and more
this.nuxt.options.extensions.push('coffee')
// Extend build

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
/*
** Headers of the page
*/

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
build: {
filenames: {
css: 'styles.[chunkhash].css', // default: common.[chunkhash].css

View File

@ -1,3 +1,3 @@
module.exports = {
export default {
loading: '~/components/loading.vue'
}

View File

@ -1,2 +1,2 @@
module.exports = {
export default {
}

View File

@ -1 +1 @@
module.exports = {}
export default {}

View File

@ -1,5 +1,7 @@
const app = require('express')()
const { Nuxt, Builder } = require('nuxt')
import express from 'express'
import { Nuxt, Builder } from 'nuxt'
const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
titleTemplate: 'Nuxt.js - Dynamic Components',
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
meta: [
{ content: 'width=device-width,initial-scale=1', name: 'viewport' }

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
meta: [
{ charset: 'utf-8' },

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
loading: { color: 'cyan' },
router: {
middleware: 'i18n'

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
css: ['~/assets/main.css'],
layoutTransition: {
name: 'layout',

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
modules: [
'@nuxtjs/markdownit'
],

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
titleTemplate: '%s - Nuxt.js',
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
router: {
middleware: ['visits', 'user-agent']
}

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
loading: false,
head: {
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
plugins: [
// ssr: false to only include it on client-side
{ src: '~/plugins/vue-notifications.js', ssr: false }

View File

@ -1,3 +1,3 @@
module.exports = {
export default {
css: ['~/assets/main.css']
}

View File

@ -1,3 +1,3 @@
module.exports = {
export default {
css: ['~/assets/main.css']
}

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
/*
** Single Page Application mode
** Means no SSR

View File

@ -1,6 +1,6 @@
const pkg = require('./package')
import pkg from './package'
module.exports = {
export default {
mode: 'universal',
/*

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
build: {
// You cannot use ~/ or @/ here since it's a Webpack plugin
styleResources: {

View File

@ -1,3 +1,3 @@
module.exports = {
export default {
css: ['~/assets/css/tailwind.css']
}

View File

@ -127,7 +127,7 @@ var colors = {
'pink-lightest': '#ffebef'
}
module.exports = {
export default {
/*
|-----------------------------------------------------------------------------

View File

@ -1,4 +1,4 @@
module.exports = function () {
export default function () {
// Add .ts extension for store, middleware and more
this.nuxt.options.extensions.push('ts')
// Extend build

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
},

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
css: ['uikit/dist/css/uikit.css'],
plugins: [
{ src: '~/plugins/uikit.js', ssr: false }

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
modules: ['@nuxtjs/apollo'],
apollo: {
networkInterfaces: {

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
title: 'Nuxt.js + Vue-ChartJS',
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
build: {
babel: {
plugins: ['transform-decorators-legacy', 'transform-class-properties']

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
/*
** We set `spa` mode to have only client-side rendering
*/

View File

@ -8,7 +8,7 @@ const modifyHtml = (html) => {
html = html.replace('</head>', ampScript + '</head>')
return html
}
module.exports = {
export default {
head: {
meta: [
{ charset: 'utf-8' },

View File

@ -1,6 +1,7 @@
import { resolve } from 'path'
import test from 'ava'
import { Nuxt, Builder } from 'nuxt'
import { resolve } from 'path'
// We keep the nuxt and server instance
// So we can close them at the end of the test

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
/*
** Customize the progress bar color
*/

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
title: 'Nuxt-Cookies',
meta: [

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
/*
** Global CSS
*/

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
loading: {
color: 'purple'
}

View File

@ -1,16 +1,14 @@
'use strict'
const path = require('path')
const compress = require('compression')
const cors = require('cors')
const feathers = require('feathers')
const configuration = require('feathers-configuration')
const hooks = require('feathers-hooks')
const rest = require('feathers-rest')
const bodyParser = require('body-parser')
const socketio = require('feathers-socketio')
const middleware = require('./middleware')
const services = require('./services')
import path from 'path'
import compress from 'compression'
import cors from 'cors'
import feathers from 'feathers'
import configuration from 'feathers-configuration'
import hooks from 'feathers-hooks'
import rest from 'feathers-rest'
import bodyParser from 'body-parser'
import socketio from 'feathers-socketio'
import middleware from './middleware'
import services from './services'
const app = feathers()
@ -27,4 +25,4 @@ app.use(compress())
.configure(services)
.configure(middleware)
module.exports = app
export default app

View File

@ -1,12 +1,10 @@
'use strict'
// Add any common hooks you want to share across services in here.
//
// Below is an example of how a hook is written and exported. Please
// see http://docs.feathersjs.com/hooks/readme.html for more details
// on hooks.
exports.myHook = function (options) {
export function myHook(options) {
return function (hook) {
console.log('My custom global hook ran. Feathers is awesome!') // eslint-disable-line no-console
}

View File

@ -1,6 +1,5 @@
'use strict'
import app from './app'
const app = require('./app')
const port = app.get('port')
process.on('nuxt:build:done', (err) => {

View File

@ -1,8 +1,6 @@
'use strict'
import nuxt from './nuxt'
const nuxt = require('./nuxt')
module.exports = function () {
export default function () {
// Add your custom middleware here. Remember, that
// just like Express the order matters, so error
// handling middleware should go last.

View File

@ -1,5 +1,5 @@
const resolve = require('path').resolve
const { Nuxt, Builder } = require('nuxt')
import { resolve } from 'path'
import { Nuxt, Builder } from 'nuxt'
// Setup nuxt.js
let config = {}
@ -18,6 +18,6 @@ if (config.dev) {
}
// Add nuxt.js middleware
module.exports = function (req, res) {
export default function (req, res) {
nuxt.render(req, res)
}

View File

@ -1,8 +1,6 @@
'use strict'
import authentication from 'feathers-authentication'
const authentication = require('feathers-authentication')
module.exports = function () {
export default function () {
const app = this
let config = app.get('auth')

View File

@ -1,8 +1,7 @@
'use strict'
const authentication = require('./authentication')
const user = require('./user')
import authentication from './authentication'
import user from './user'
module.exports = function () {
export default function () {
const app = this
app.configure(authentication)

View File

@ -1,8 +1,7 @@
'use strict'
import hooks from 'feathers-hooks'
import { hooks as auth } from 'feathers-authentication'
require('../../../hooks')
const hooks = require('feathers-hooks')
const auth = require('feathers-authentication').hooks
exports.before = {
all: [],

View File

@ -1,11 +1,9 @@
'use strict'
import path from 'path'
import NeDB from 'nedb'
import service from 'feathers-nedb'
import hooks from './hooks'
const path = require('path')
const NeDB = require('nedb')
const service = require('feathers-nedb')
const hooks = require('./hooks')
module.exports = function () {
export default function () {
const app = this
const db = new NeDB({

View File

@ -1,8 +1,6 @@
'use strict'
const assert = require('assert')
const request = require('request')
const app = require('../src/app')
import assert from 'assert'
import request from 'request'
import app from '../src/app'
describe('Feathers application tests', function () {
before(function (done) {

View File

@ -1,7 +1,5 @@
'use strict'
const assert = require('assert')
const app = require('../../../src/app')
import assert from 'assert'
import app from '../../../src/app'
describe('user service', function () {
it('registered the users service', () => {

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
meta: [
{ charset: 'utf-8' },

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
meta: [
{

View File

@ -1,6 +1,6 @@
const path = require('path')
const PurgecssPlugin = require('purgecss-webpack-plugin')
const glob = require('glob-all')
import path from 'path'
import PurgecssPlugin from 'purgecss-webpack-plugin'
import glob from 'glob-all'
class TailwindExtractor {
static extract(content) {
@ -8,7 +8,7 @@ class TailwindExtractor {
}
}
module.exports = {
export default {
build: {
extractCSS: true,
postcss: [

View File

@ -127,7 +127,7 @@ var colors = {
'pink-lightest': '#ffebef'
}
module.exports = {
export default {
/*
|-----------------------------------------------------------------------------

View File

@ -1,7 +1,10 @@
module.exports = function () {
const server = require('http').createServer(this.nuxt.renderer.app)
const io = require('socket.io')(server)
import http from 'http'
import socketIO from 'socket.io'
const server = http.createServer(this.nuxt.renderer.app)
const io = socketIO(server)
export default function () {
// overwrite nuxt.listen()
this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve))
// close this server on 'close' event

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
meta: [
{ charset: 'utf-8' },

View File

@ -1,10 +1,16 @@
const { Nuxt, Builder } = require('nuxt')
const app = require('express')()
const server = require('http').createServer(app)
const io = require('socket.io')(server)
import http from 'http'
import { Nuxt, Builder } from 'nuxt'
import express from 'express'
import SocketIO from 'socket.io'
const port = process.env.PORT || 3000
const isProd = process.env.NODE_ENV === 'production'
const app = express()
const server = http.createServer(app)
const io = SocketIO(server)
// We instantiate Nuxt.js with the options
let config = require('./nuxt.config.js')
config.dev = !isProd

View File

@ -1,4 +1,4 @@
const hooks = require('require-extension-hooks')
import hooks from 'require-extension-hooks'
// Setup browser environment
require('browser-env')()

View File

@ -1,4 +1,4 @@
module.exports = {
export default {
head: {
meta: [
{

View File

@ -1,6 +1,6 @@
const nodeExternals = require('webpack-node-externals')
import nodeExternals from 'webpack-node-externals'
module.exports = {
export default {
/*
** Head elements
** Add Roboto font and Material Icons

View File

@ -1,7 +1,8 @@
const vuxLoader = require('vux-loader')
const path = require('path')
import path from 'path'
module.exports = {
import vuxLoader from 'vux-loader'
export default {
head: {
meta: [
{ charset: 'utf-8' },

View File

@ -1,29 +1,32 @@
const { promisify } = require('util')
const _ = require('lodash')
const chokidar = require('chokidar')
const { remove, readFile, writeFile, mkdirp, existsSync } = require('fs-extra')
const fs = require('fs')
const hash = require('hash-sum')
const webpack = require('webpack')
const serialize = require('serialize-javascript')
const { join, resolve, basename, extname, dirname } = require('path')
const MFS = require('memory-fs')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const Debug = require('debug')
const Glob = require('glob')
const { r, wp, wChunk, createRoutes, parallel, relativeTo, waitFor, createSpinner } = require('../common/utils')
const { Options } = require('../common')
const clientWebpackConfig = require('./webpack/client.config.js')
const serverWebpackConfig = require('./webpack/server.config.js')
const upath = require('upath')
import util from 'util'
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
import chokidar from 'chokidar'
import fsExtra from 'fs-extra'
import hash from 'hash-sum'
import webpack from 'webpack'
import serialize from 'serialize-javascript'
import MFS from 'memory-fs'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import Debug from 'debug'
import Glob from 'glob'
import upath from 'upath'
import { r, wp, wChunk, createRoutes, parallel, relativeTo, waitFor, createSpinner } from '../common/utils'
import Options from '../common/options'
import clientWebpackConfig from './webpack/client.config'
import serverWebpackConfig from './webpack/server.config'
const debug = Debug('nuxt:build')
debug.color = 2 // Force green color
const glob = promisify(Glob)
const glob = util.promisify(Glob)
module.exports = class Builder {
export default class Builder {
constructor(nuxt) {
this.nuxt = nuxt
this.isStatic = false // Flag to know if the build is for a generated app
@ -61,7 +64,7 @@ module.exports = class Builder {
return _.uniqBy(
this.options.plugins.map((p, i) => {
if (typeof p === 'string') p = { src: p }
const pluginBaseName = basename(p.src, extname(p.src)).replace(
const pluginBaseName = path.basename(p.src, path.extname(p.src)).replace(
/[^a-zA-Z?\d\s:]/g,
''
)
@ -104,9 +107,9 @@ module.exports = class Builder {
// Check if pages dir exists and warn if not
this._nuxtPages = typeof this.options.build.createRoutes !== 'function'
if (this._nuxtPages) {
if (!existsSync(join(this.options.srcDir, this.options.dir.pages))) {
if (!fsExtra.existsSync(path.join(this.options.srcDir, this.options.dir.pages))) {
let dir = this.options.srcDir
if (existsSync(join(this.options.srcDir, '..', this.options.dir.pages))) {
if (fsExtra.existsSync(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?`
)
@ -123,10 +126,10 @@ module.exports = class Builder {
debug(`App root: ${this.options.srcDir}`)
// Create .nuxt/, .nuxt/components and .nuxt/dist folders
await remove(r(this.options.buildDir))
await mkdirp(r(this.options.buildDir, 'components'))
await fsExtra.remove(r(this.options.buildDir))
await fsExtra.mkdirp(r(this.options.buildDir, 'components'))
if (!this.options.dev) {
await mkdirp(r(this.options.buildDir, 'dist'))
await fsExtra.mkdirp(r(this.options.buildDir, 'dist'))
}
// Generate routes and interpret the template files
@ -156,7 +159,7 @@ module.exports = class Builder {
if (!options.babelrc && !options.presets) {
options.presets = [
[
require.resolve('babel-preset-vue-app'),
'babel-preset-vue-app',
{
targets: isServer ? { node: '8.0.0' } : { ie: 9, uglify: true }
}
@ -215,7 +218,7 @@ module.exports = class Builder {
router: this.options.router,
env: this.options.env,
head: this.options.head,
middleware: existsSync(join(this.options.srcDir, this.options.dir.middleware)),
middleware: fsExtra.existsSync(path.join(this.options.srcDir, this.options.dir.middleware)),
store: this.options.store,
css: this.options.css,
plugins: this.plugins,
@ -237,7 +240,7 @@ module.exports = class Builder {
}
// -- Layouts --
if (existsSync(resolve(this.options.srcDir, this.options.dir.layouts))) {
if (fsExtra.existsSync(path.resolve(this.options.srcDir, this.options.dir.layouts))) {
const layoutsFiles = await glob(`${this.options.dir.layouts}/**/*.{vue,js}`, {
cwd: this.options.srcDir,
ignore: this.options.ignore
@ -269,7 +272,7 @@ module.exports = class Builder {
}
// If no default layout, create its folder and add the default folder
if (!templateVars.layouts.default) {
await mkdirp(r(this.options.buildDir, 'layouts'))
await fsExtra.mkdirp(r(this.options.buildDir, 'layouts'))
templatesFiles.push('layouts/default.vue')
templateVars.layouts.default = './layouts/default.vue'
}
@ -330,7 +333,7 @@ module.exports = class Builder {
// Resolve template files
const customTemplateFiles = this.options.build.templates.map(
t => t.dst || basename(t.src || t)
t => t.dst || path.basename(t.src || t)
)
templatesFiles = templatesFiles
@ -341,7 +344,7 @@ module.exports = class Builder {
}
// Allow override templates using a file with same name in ${srcDir}/app
const customPath = r(this.options.srcDir, 'app', file)
const customFileExists = existsSync(customPath)
const customFileExists = fsExtra.existsSync(customPath)
return {
src: customFileExists ? customPath : r(this.options.nuxtAppDir, file),
@ -358,7 +361,7 @@ module.exports = class Builder {
return Object.assign(
{
src: r(this.options.srcDir, t.src || t),
dst: t.dst || basename(t.src || t),
dst: t.dst || path.basename(t.src || t),
custom: true
},
t
@ -368,7 +371,7 @@ module.exports = class Builder {
// -- Loading indicator --
if (this.options.loadingIndicator.name) {
const indicatorPath1 = resolve(
const indicatorPath1 = path.resolve(
this.options.nuxtAppDir,
'views/loading',
this.options.loadingIndicator.name + '.html'
@ -376,9 +379,9 @@ module.exports = class Builder {
const indicatorPath2 = this.nuxt.resolveAlias(
this.options.loadingIndicator.name
)
const indicatorPath = existsSync(indicatorPath1)
const indicatorPath = fsExtra.existsSync(indicatorPath1)
? indicatorPath1
: existsSync(indicatorPath2) ? indicatorPath2 : null
: fsExtra.existsSync(indicatorPath2) ? indicatorPath2 : null
if (indicatorPath) {
templatesFiles.push({
src: indicatorPath,
@ -408,7 +411,7 @@ module.exports = class Builder {
// Add template to watchers
this.options.build.watch.push(src)
// Render template to dst
const fileContent = await readFile(src, 'utf8')
const fileContent = await fsExtra.readFile(src, 'utf8')
let content
try {
const template = _.template(fileContent, {
@ -435,11 +438,11 @@ module.exports = class Builder {
/* istanbul ignore next */
throw new Error(`Could not compile template ${src}: ${err.message}`)
}
const path = r(this.options.buildDir, dst)
const _path = r(this.options.buildDir, dst)
// Ensure parent dir exits
await mkdirp(dirname(path))
await fsExtra.mkdirp(path.dirname(_path))
// Write file
await writeFile(path, content, 'utf8')
await fsExtra.writeFile(_path, content, 'utf8')
})
)
@ -544,7 +547,7 @@ module.exports = class Builder {
debug('Adding webpack middleware...')
// Create webpack dev middleware
this.webpackDevMiddleware = promisify(
this.webpackDevMiddleware = util.promisify(
webpackDevMiddleware(
compiler,
Object.assign(
@ -559,9 +562,9 @@ module.exports = class Builder {
)
)
this.webpackDevMiddleware.close = promisify(this.webpackDevMiddleware.close)
this.webpackDevMiddleware.close = util.promisify(this.webpackDevMiddleware.close)
this.webpackHotMiddleware = promisify(
this.webpackHotMiddleware = util.promisify(
webpackHotMiddleware(
compiler,
Object.assign(
@ -644,11 +647,11 @@ module.exports = class Builder {
// TODO: remove ignore when generateConfig enabled again
async generateConfig() /* istanbul ignore next */ {
const config = resolve(this.options.buildDir, 'build.config.js')
const config = path.resolve(this.options.buildDir, 'build.config.js')
const options = _.omit(this.options, Options.unsafeKeys)
await writeFile(
await fsExtra.writeFile(
config,
`module.exports = ${JSON.stringify(options, null, ' ')}`,
`export default ${JSON.stringify(options, null, ' ')}`,
'utf8'
)
}

View File

@ -1,36 +1,21 @@
const {
copy,
remove,
writeFile,
mkdirp,
removeSync,
existsSync
} = require('fs-extra')
const _ = require('lodash')
const { resolve, join, dirname, sep } = require('path')
const { minify } = require('html-minifier')
const Chalk = require('chalk')
const { printWarn, createSpinner } = require('../common/utils')
import path from 'path'
import _ from 'lodash'
import htmlMinifier from 'html-minifier'
import Chalk from 'chalk'
import fsExtra from 'fs-extra'
import { isUrl, promisifyRoute, waitFor, flatRoutes, printWarn, createSpinner } from '../common/utils'
const {
isUrl,
promisifyRoute,
waitFor,
flatRoutes,
pe
} = require('../common/utils')
module.exports = class Generator {
export default class Generator {
constructor(nuxt, builder) {
this.nuxt = nuxt
this.options = nuxt.options
this.builder = builder
// Set variables
this.staticRoutes = resolve(this.options.srcDir, this.options.dir.static)
this.srcBuiltPath = resolve(this.options.buildDir, 'dist')
this.distPath = resolve(this.options.rootDir, this.options.generate.dir)
this.distNuxtPath = join(
this.staticRoutes = path.resolve(this.options.srcDir, this.options.dir.static)
this.srcBuiltPath = path.resolve(this.options.buildDir, 'dist')
this.distPath = path.resolve(this.options.rootDir, this.options.generate.dir)
this.distNuxtPath = path.join(
this.distPath,
isUrl(this.options.build.publicPath) ? '' : this.options.build.publicPath
)
@ -137,12 +122,12 @@ module.exports = class Generator {
const color = isHandled ? 'yellow' : 'red'
let line =
Chalk.black[bgColor](' GENERATE ERR ') + Chalk[color](` ${route}\n\n`)
Chalk.black[bgColor](' GEN ERR ') + Chalk[color](` ${route}\n\n`)
if (isHandled) {
line += Chalk.grey(JSON.stringify(error, undefined, 2) + '\n')
} else {
line += Chalk.grey(pe.render(error))
line += Chalk.grey(error.stack)
}
return line
@ -156,36 +141,36 @@ module.exports = class Generator {
// Disable SPA fallback if value isn't true or a string
if (fallback !== true && typeof fallback !== 'string') return
const fallbackPath = join(this.distPath, fallback)
const fallbackPath = path.join(this.distPath, fallback)
// Prevent conflicts
if (existsSync(fallbackPath)) {
if (fsExtra.existsSync(fallbackPath)) {
printWarn(`SPA fallback was configured, but the configured path (${fallbackPath}) already exists.`)
return
}
// Render and write the SPA template to the fallback path
const { html } = await this.nuxt.renderRoute('/', { spa: true })
await writeFile(fallbackPath, html, 'utf8')
await fsExtra.writeFile(fallbackPath, html, 'utf8')
}
async initDist() {
// Clean destination folder
await remove(this.distPath)
await fsExtra.remove(this.distPath)
await this.nuxt.callHook('generate:distRemoved', this)
// Copy static and built files
/* istanbul ignore if */
if (existsSync(this.staticRoutes)) {
await copy(this.staticRoutes, this.distPath)
if (fsExtra.existsSync(this.staticRoutes)) {
await fsExtra.copy(this.staticRoutes, this.distPath)
}
await copy(this.srcBuiltPath, this.distNuxtPath)
await fsExtra.copy(this.srcBuiltPath, this.distNuxtPath)
// Add .nojekyll file to let Github Pages add the _nuxt/ folder
// https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/
const nojekyllPath = resolve(this.distPath, '.nojekyll')
writeFile(nojekyllPath, '')
const nojekyllPath = path.resolve(this.distPath, '.nojekyll')
fsExtra.writeFile(nojekyllPath, '')
// Cleanup SSR related files
const extraFiles = [
@ -193,11 +178,11 @@ module.exports = class Generator {
'index.ssr.html',
'server-bundle.json',
'vue-ssr-client-manifest.json'
].map(file => resolve(this.distNuxtPath, file))
].map(file => path.resolve(this.distNuxtPath, file))
extraFiles.forEach(file => {
if (existsSync(file)) {
removeSync(file)
if (fsExtra.existsSync(file)) {
fsExtra.removeSync(file)
}
})
@ -253,7 +238,7 @@ module.exports = class Generator {
if (this.options.generate.minify) {
try {
html = minify(html, this.options.generate.minify)
html = htmlMinifier.minify(html, this.options.generate.minify)
} catch (err) /* istanbul ignore next */ {
const minifyErr = new Error(
`HTML minification failed. Make sure the route generates valid HTML. Failed HTML:\n ${html}`
@ -262,25 +247,24 @@ module.exports = class Generator {
}
}
let path
let _path
if (this.options.generate.subFolders) {
path = join(route, sep, 'index.html') // /about -> /about/index.html
path = path === '/404/index.html' ? '/404.html' : path // /404 -> /404.html
_path = path.join(route, path.sep, 'index.html') // /about -> /about/index.html
_path = _path === '/404/index.html' ? '/404.html' : _path // /404 -> /404.html
} else {
path =
route.length > 1 ? join(sep, route + '.html') : join(sep, 'index.html')
_path = route.length > 1 ? path.join(path.sep, route + '.html') : path.join(path.sep, 'index.html')
}
// Call hook to let user update the path & html
const page = { route, path, html }
const page = { route, path: _path, html }
await this.nuxt.callHook('generate:page', page)
page.path = join(this.distPath, page.path)
page.path = path.join(this.distPath, page.path)
// Make sure the sub folders are created
await mkdirp(dirname(page.path))
await writeFile(page.path, page.html, 'utf8')
await fsExtra.mkdirp(path.dirname(page.path))
await fsExtra.writeFile(page.path, page.html, 'utf8')
await this.nuxt.callHook('generate:routeCreated', {
route,

View File

@ -1,7 +0,0 @@
const Builder = require('./builder')
const Generator = require('./generator')
module.exports = {
Builder,
Generator
}

7
lib/builder/index.mjs Normal file
View File

@ -0,0 +1,7 @@
import Builder from './builder'
import Generator from './generator'
export default {
Builder,
Generator
}

View File

@ -1,16 +1,15 @@
const TimeFixPlugin = require('time-fix-plugin')
const WarnFixPlugin = require('./plugins/warnfix')
const ProgressPlugin = require('./plugins/progress')
const FriendlyErrorsWebpackPlugin = require('@nuxtjs/friendly-errors-webpack-plugin')
import path from 'path'
const webpack = require('webpack')
const { cloneDeep } = require('lodash')
const { join, resolve } = require('path')
import TimeFixPlugin from 'time-fix-plugin'
import webpack from 'webpack'
import _ from 'lodash'
const { isUrl, urlJoin } = require('../../common/utils')
import { isUrl, urlJoin } from '../../common/utils'
const vueLoader = require('./vue-loader')
const styleLoader = require('./style-loader')
import WarnFixPlugin from './plugins/warnfix'
import ProgressPlugin from './plugins/progress'
import vueLoader from './vue-loader'
import styleLoader from './style-loader'
/*
|--------------------------------------------------------------------------
@ -20,7 +19,7 @@ const styleLoader = require('./style-loader')
| webpack config files
|--------------------------------------------------------------------------
*/
module.exports = function webpackBaseConfig({ name, isServer }) {
export default function webpackBaseConfig({ name, isServer }) {
// Prioritize nested node_modules in webpack search path (#2558)
const webpackModulesDir = ['node_modules'].concat(this.options.modulesDir)
@ -28,11 +27,11 @@ module.exports = function webpackBaseConfig({ name, isServer }) {
// Used by vue-loader so we can use in templates
// with <img src="~/assets/nuxt.png"/>
configAlias[this.options.dir.assets] = join(
configAlias[this.options.dir.assets] = path.join(
this.options.srcDir,
this.options.dir.assets
)
configAlias[this.options.dir.static] = join(
configAlias[this.options.dir.static] = path.join(
this.options.srcDir,
this.options.dir.static
)
@ -42,7 +41,7 @@ module.exports = function webpackBaseConfig({ name, isServer }) {
mode: this.options.dev ? 'development' : 'production',
optimization: {},
output: {
path: resolve(this.options.buildDir, 'dist'),
path: path.resolve(this.options.buildDir, 'dist'),
filename: this.getFileName('app'),
chunkFilename: this.getFileName('chunk'),
jsonpFunction: '_NXT_',
@ -58,10 +57,10 @@ module.exports = function webpackBaseConfig({ name, isServer }) {
extensions: ['.js', '.json', '.vue', '.jsx'],
alias: Object.assign(
{
'~': join(this.options.srcDir),
'~~': join(this.options.rootDir),
'@': join(this.options.srcDir),
'@@': join(this.options.rootDir)
'~': path.join(this.options.srcDir),
'~~': path.join(this.options.rootDir),
'@': path.join(this.options.srcDir),
'@@': path.join(this.options.rootDir)
},
configAlias
),
@ -155,5 +154,5 @@ module.exports = function webpackBaseConfig({ name, isServer }) {
)
// Clone deep avoid leaking config between Client and Server
return cloneDeep(config)
return _.cloneDeep(config)
}

View File

@ -1,14 +1,17 @@
const { each } = require('lodash')
const webpack = require('webpack')
// const VueSSRClientPlugin = require('vue-server-renderer/client-plugin')
const VueSSRClientPlugin = require('./plugins/vue/client')
const HTMLPlugin = require('html-webpack-plugin')
const StylishPlugin = require('webpack-stylish')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const { resolve } = require('path')
const Debug = require('debug')
const base = require('./base.config.js')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
import path from 'path'
import _ from 'lodash'
import webpack from 'webpack'
import HTMLPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import StylishPlugin from 'webpack-stylish'
import BundleAnalyzer from 'webpack-bundle-analyzer'
import Debug from 'debug'
import base from './base.config'
// import VueSSRClientPlugin from 'vue-server-renderer/client-plugin'
import VueSSRClientPlugin from './plugins/vue/client'
const debug = Debug('nuxt:build')
debug.color = 2 // Force green color
@ -18,15 +21,15 @@ debug.color = 2 // Force green color
| Webpack Client Config
|--------------------------------------------------------------------------
*/
module.exports = function webpackClientConfig() {
export default function webpackClientConfig() {
let config = base.call(this, { name: 'client', isServer: false })
// Entry points
config.entry = resolve(this.options.buildDir, 'client.js')
config.entry = path.resolve(this.options.buildDir, 'client.js')
// Env object defined in nuxt.config.js
let env = {}
each(this.options.env, (value, key) => {
_.each(this.options.env, (value, key) => {
env['process.env.' + key] =
['boolean', 'number'].indexOf(typeof value) !== -1
? value
@ -176,7 +179,7 @@ module.exports = function webpackClientConfig() {
// Webpack Bundle Analyzer
if (this.options.build.analyze) {
config.plugins.push(
new BundleAnalyzerPlugin(Object.assign({}, this.options.build.analyze))
new BundleAnalyzer.BundleAnalyzerPlugin(Object.assign({}, this.options.build.analyze))
)
}
}

View File

@ -1,12 +1,12 @@
const webpack = require('webpack')
const chalk = require('chalk')
const _ = require('lodash')
import webpack from 'webpack'
import chalk from 'chalk'
import _ from 'lodash'
const sharedState = {}
const BLOCK_CHAR = '█'
module.exports = class ProgressPlugin extends webpack.ProgressPlugin {
export default class ProgressPlugin extends webpack.ProgressPlugin {
constructor(options) {
super(options)

View File

@ -1,8 +1,8 @@
const hash = require('hash-sum')
const uniq = require('lodash.uniq')
const { isJS, onEmit } = require('./util')
import hash from 'hash-sum'
import uniq from 'lodash.uniq'
import { isJS, onEmit } from './util'
module.exports = class VueSSRClientPlugin {
export default class VueSSRClientPlugin {
constructor(options = {}) {
this.options = Object.assign({
filename: 'vue-ssr-client-manifest.json'

View File

@ -1,6 +1,6 @@
const { validate, isJS, onEmit } = require('./util')
import { validate, isJS, onEmit } from './util'
module.exports = class VueSSRServerPlugin {
export default class VueSSRServerPlugin {
constructor(options = {}) {
this.options = Object.assign({
filename: 'vue-ssr-server-bundle.json'

View File

@ -1,10 +1,10 @@
const { red, yellow } = require('chalk')
import chalk from 'chalk'
const prefix = `[vue-server-renderer-webpack-plugin]`
const warn = exports.warn = msg => console.error(red(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
const tip = exports.tip = msg => console.log(yellow(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
export const warn = msg => console.error(chalk.red(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
export const tip = msg => console.log(chalk.yellow(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
exports.validate = compiler => {
export const validate = compiler => {
if (compiler.options.target !== 'node') {
warn('webpack config `target` should be "node".')
}
@ -21,7 +21,7 @@ exports.validate = compiler => {
}
}
exports.onEmit = (compiler, name, hook) => {
export const onEmit = (compiler, name, hook) => {
if (compiler.hooks) {
// Webpack >= 4.0.0
compiler.hooks.emit.tapAsync(name, hook)
@ -31,6 +31,6 @@ exports.onEmit = (compiler, name, hook) => {
}
}
exports.isJS = (file) => /\.js(\?[^.]+)?$/.test(file)
export const isJS = (file) => /\.js(\?[^.]+)?$/.test(file)
exports.isCSS = (file) => /\.css(\?[^.]+)?$/.test(file)
export const isCSS = (file) => /\.css(\?[^.]+)?$/.test(file)

View File

@ -1,4 +1,4 @@
module.exports = class WarnFixPlugin {
export default class WarnFixPlugin {
apply(compiler) /* istanbul ignore next */ {
compiler.hooks.done.tap('warnfix-plugin', stats => {
stats.compilation.warnings = stats.compilation.warnings.filter(warn => {

View File

@ -1,11 +1,13 @@
const { existsSync } = require('fs')
const { resolve, join } = require('path')
const { cloneDeep } = require('lodash')
const { isPureObject } = require('../../common/utils')
const createResolver = require('postcss-import-resolver')
import fs from 'fs'
import path from 'path'
module.exports = function postcssConfig() {
let config = cloneDeep(this.options.build.postcss)
import ـ from 'lodash'
import createResolver from 'postcss-import-resolver'
import { isPureObject } from '../../common/utils'
export default function postcssConfig() {
let config = ـ.cloneDeep(this.options.build.postcss)
/* istanbul ignore if */
if (!config) {
@ -22,8 +24,8 @@ module.exports = function postcssConfig() {
'.postcssrc.json',
'.postcssrc.yaml'
]) {
if (existsSync(resolve(dir, file))) {
const postcssConfigPath = resolve(dir, file)
if (fs.existsSync(path.resolve(dir, file))) {
const postcssConfigPath = path.resolve(dir, file)
return {
sourceMap: this.options.build.cssSourceMap,
config: {
@ -50,10 +52,10 @@ module.exports = function postcssConfig() {
'postcss-import': {
resolve: createResolver({
alias: {
'~': join(this.options.srcDir),
'~~': join(this.options.rootDir),
'@': join(this.options.srcDir),
'@@': join(this.options.rootDir)
'~': path.join(this.options.srcDir),
'~~': path.join(this.options.rootDir),
'@': path.join(this.options.srcDir),
'@@': path.join(this.options.rootDir)
},
modules: [
this.options.srcDir,
@ -78,7 +80,7 @@ module.exports = function postcssConfig() {
if (isPureObject(config) && isPureObject(config.plugins)) {
config.plugins = Object.keys(config.plugins)
.map(p => {
const plugin = require(this.nuxt.resolvePath(p))
const plugin = this.nuxt.requireModule(p)
const opts = config.plugins[p]
if (opts === false) return // Disabled
const instance = plugin(opts)

View File

@ -1,23 +1,26 @@
const webpack = require('webpack')
// const VueSSRServerPlugin = require('vue-server-renderer/server-plugin')
const VueSSRServerPlugin = require('./plugins/vue/server')
const nodeExternals = require('webpack-node-externals')
const { each } = require('lodash')
const { resolve } = require('path')
const { existsSync } = require('fs')
const base = require('./base.config.js')
import path from 'path'
import fs from 'fs'
import webpack from 'webpack'
import nodeExternals from 'webpack-node-externals'
import _ from 'lodash'
import base from './base.config'
// import VueSSRServerPlugin from 'vue-server-renderer/server-plugin'
import VueSSRServerPlugin from './plugins/vue/server'
/*
|--------------------------------------------------------------------------
| Webpack Server Config
|--------------------------------------------------------------------------
*/
module.exports = function webpackServerConfig() {
export default function webpackServerConfig() {
let config = base.call(this, { name: 'server', isServer: true })
// Env object defined in nuxt.config.js
let env = {}
each(this.options.env, (value, key) => {
_.each(this.options.env, (value, key) => {
env['process.env.' + key] =
['boolean', 'number'].indexOf(typeof value) !== -1
? value
@ -30,7 +33,7 @@ module.exports = function webpackServerConfig() {
config = Object.assign(config, {
target: 'node',
node: false,
entry: resolve(this.options.buildDir, 'server.js'),
entry: path.resolve(this.options.buildDir, 'server.js'),
output: Object.assign({}, config.output, {
filename: 'server-bundle.js',
libraryTarget: 'commonjs2'
@ -60,7 +63,7 @@ module.exports = function webpackServerConfig() {
// https://webpack.js.org/configuration/externals/#externals
// https://github.com/liady/webpack-node-externals
this.options.modulesDir.forEach(dir => {
if (existsSync(dir)) {
if (fs.existsSync(dir)) {
config.externals.push(
nodeExternals({
// load non-javascript files with extensions, presumably via loaders

View File

@ -1,8 +1,10 @@
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const { join } = require('path')
const postcssConfig = require('./postcss')
import path from 'path'
module.exports = function styleLoader(ext, loaders = [], isVueLoader = false) {
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import postcssConfig from './postcss'
export default function styleLoader(ext, loaders = [], isVueLoader = false) {
const sourceMap = Boolean(this.options.build.cssSourceMap)
// Normalize loaders
@ -57,8 +59,8 @@ module.exports = function styleLoader(ext, loaders = [], isVueLoader = false) {
// css-loader
// https://github.com/webpack-contrib/css-loader
const cssLoaderAlias = {}
cssLoaderAlias[`/${this.options.dir.assets}`] = join(this.options.srcDir, this.options.dir.assets)
cssLoaderAlias[`/${this.options.dir.static}`] = join(this.options.srcDir, this.options.dir.static)
cssLoaderAlias[`/${this.options.dir.assets}`] = path.join(this.options.srcDir, this.options.dir.assets)
cssLoaderAlias[`/${this.options.dir.static}`] = path.join(this.options.srcDir, this.options.dir.static)
loaders.unshift({
loader: 'css-loader',

View File

@ -1,7 +1,7 @@
const postcssConfig = require('./postcss')
const styleLoader = require('./style-loader')
import postcssConfig from './postcss'
import styleLoader from './style-loader'
module.exports = function vueLoader({ isServer }) {
export default function vueLoader({ isServer }) {
// https://vue-loader.vuejs.org/en
const config = {
postcss: postcssConfig.call(this),

View File

@ -1,7 +0,0 @@
const Utils = require('./utils')
const Options = require('./options')
module.exports = {
Utils,
Options
}

18
lib/common/modes.mjs Normal file
View File

@ -0,0 +1,18 @@
export default {
universal: {
build: {
ssr: true
},
render: {
ssr: true
}
},
spa: {
build: {
ssr: false
},
render: {
ssr: false
}
}
}

8
lib/common/module.js Normal file
View File

@ -0,0 +1,8 @@
const esm = require('esm')
const _esm = esm(module, {})
exports.requireModule = function requireModule() {
const m = _esm.apply(this, arguments)
return (m && m.default) || m
}

176
lib/common/nuxt.config.js Normal file
View File

@ -0,0 +1,176 @@
import path from 'path'
export default {
mode: 'universal',
dev: process.env.NODE_ENV !== 'production',
debug: undefined, // Will be equal to dev if not provided
buildDir: '.nuxt',
cacheDir: '.cache',
nuxtDir: path.resolve(__dirname, '../..'),
nuxtAppDir: path.resolve(__dirname, '../app'),
modulesDir: ['node_modules'], // ~> relative to options.rootDir
ignorePrefix: '-',
ignore: [
'**/*.test.*'
],
extensions: [],
build: {
analyze: false,
profile: process.argv.includes('--profile'),
splitPages: true,
maxChunkSize: false,
extractCSS: false,
cssSourceMap: undefined,
ssr: undefined,
publicPath: '/_nuxt/',
filenames: {
app: '[name].[chunkhash].js',
chunk: '[name].[chunkhash].js',
css: '[name].[contenthash].css'
},
styleResources: {},
plugins: [],
babel: {
babelrc: false
},
postcss: {},
templates: [],
watch: [],
devMiddleware: {},
hotMiddleware: {},
stats: {
chunks: false,
children: false,
modules: false,
colors: true,
excludeAssets: [
/.map$/,
/index\..+\.html$/,
/vue-ssr-client-manifest.json/
]
}
},
generate: {
dir: 'dist',
routes: [],
concurrency: 500,
interval: 0,
subFolders: true,
fallback: '200.html',
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: false,
decodeEntities: true,
minifyCSS: true,
minifyJS: true,
processConditionalComments: true,
removeAttributeQuotes: false,
removeComments: false,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: false,
removeStyleLinkTypeAttributes: false,
removeTagWhitespace: false,
sortAttributes: true,
sortClassName: false,
trimCustomFragments: true,
useShortDoctype: true
}
},
env: {},
head: {
meta: [],
link: [],
style: [],
script: []
},
plugins: [],
css: [],
modules: [],
layouts: {},
serverMiddleware: [],
ErrorPage: null,
loading: {
color: 'black',
failedColor: 'red',
height: '2px',
duration: 5000,
rtl: false
},
loadingIndicator: {},
transition: {
name: 'page',
mode: 'out-in',
appear: false,
appearClass: 'appear',
appearActiveClass: 'appear-active',
appearToClass: 'appear-to'
},
layoutTransition: {
name: 'layout',
mode: 'out-in'
},
dir: {
assets: 'assets',
layouts: 'layouts',
middleware: 'middleware',
pages: 'pages',
static: 'static',
store: 'store'
},
router: {
mode: 'history',
base: '/',
routes: [],
middleware: [],
linkActiveClass: 'nuxt-link-active',
linkExactActiveClass: 'nuxt-link-exact-active',
extendRoutes: null,
scrollBehavior: null,
parseQuery: false,
stringifyQuery: false,
fallback: false
},
render: {
bundleRenderer: {},
resourceHints: true,
ssr: undefined,
http2: {
push: false,
shouldPush: null
},
static: {
prefix: true
},
gzip: {
threshold: 0
},
etag: {
weak: false
},
csp: {
enabled: false,
hashAlgorithm: 'sha256',
allowedSources: undefined,
policies: undefined
}
},
watchers: {
webpack: {},
chokidar: {}
},
editor: undefined,
hooks: null,
messages: {
error_404: 'This page could not be found',
server_error: 'Server error',
nuxtjs: 'Nuxt.js',
back_to_home: 'Back to the home page',
server_error_details:
'An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.',
client_error: 'Error',
client_error_details:
'An error occurred while rendering the page. Check developer tools console for details.'
}
}

View File

@ -1,356 +0,0 @@
const _ = require('lodash')
const Debug = require('debug')
const { join, resolve } = require('path')
const { existsSync, readdirSync } = require('fs')
const { isUrl, isPureObject } = require('../common/utils')
const debug = Debug('nuxt:build')
debug.color = 2 // Force green color
const Options = {}
module.exports = Options
Options.from = function (_options) {
// Clone options to prevent unwanted side-effects
const options = Object.assign({}, _options)
// Normalize options
if (options.loading === true) {
delete options.loading
}
if (
options.router &&
options.router.middleware &&
!Array.isArray(options.router.middleware)
) {
options.router.middleware = [options.router.middleware]
}
if (options.router && typeof options.router.base === 'string') {
options._routerBaseSpecified = true
}
if (typeof options.transition === 'string') {
options.transition = { name: options.transition }
}
if (typeof options.layoutTransition === 'string') {
options.layoutTransition = { name: options.layoutTransition }
}
if (typeof options.extensions === 'string') {
options.extensions = [options.extensions]
}
const hasValue = v => typeof v === 'string' && v
options.rootDir = hasValue(options.rootDir) ? options.rootDir : process.cwd()
// Apply defaults by ${buildDir}/dist/build.config.js
// TODO: Unsafe operation.
// const buildDir = options.buildDir || Options.defaults.buildDir
// const buildConfig = resolve(options.rootDir, buildDir, 'build.config.js')
// if (existsSync(buildConfig)) {
// _.defaultsDeep(options, require(buildConfig))
// }
// Apply defaults
_.defaultsDeep(options, Options.defaults)
// Resolve dirs
options.srcDir = hasValue(options.srcDir)
? resolve(options.rootDir, options.srcDir)
: options.rootDir
options.buildDir = resolve(options.rootDir, options.buildDir)
options.cacheDir = resolve(options.rootDir, options.cacheDir)
// Populate modulesDir
options.modulesDir = []
.concat(options.modulesDir)
.concat(join(options.nuxtDir, 'node_modules'))
.filter(dir => hasValue(dir))
.map(dir => resolve(options.rootDir, dir))
// Sanitize extensions
if (options.extensions.indexOf('js') === -1) {
options.extensions.unshift('js')
}
// If app.html is defined, set the template path to the user template
options.appTemplatePath = resolve(options.buildDir, 'views/app.template.html')
if (existsSync(join(options.srcDir, 'app.html'))) {
options.appTemplatePath = join(options.srcDir, 'app.html')
}
// Ignore publicPath on dev
/* istanbul ignore if */
if (options.dev && isUrl(options.build.publicPath)) {
options.build.publicPath = Options.defaults.build.publicPath
}
// If store defined, update store options to true unless explicitly disabled
if (
options.store !== false &&
existsSync(join(options.srcDir, options.dir.store)) &&
readdirSync(join(options.srcDir, options.dir.store))
.find(filename => filename !== 'README.md' && filename[0] !== '.')
) {
options.store = true
}
// Normalize loadingIndicator
if (!isPureObject(options.loadingIndicator)) {
options.loadingIndicator = { name: options.loadingIndicator }
}
// Apply default hash to CSP option
if (options.render.csp === true) {
options.render.csp = { hashAlgorithm: 'sha256' }
}
// Apply defaults to loadingIndicator
options.loadingIndicator = Object.assign(
{
name: 'pulse',
color: '#dbe1ec',
background: 'white'
},
options.loadingIndicator
)
// cssSourceMap
if (options.build.cssSourceMap === undefined) {
options.build.cssSourceMap = options.dev
}
// babel cacheDirectory
if (options.build.babel.cacheDirectory === undefined) {
options.build.babel.cacheDirectory = options.dev
}
// Debug errors
if (options.debug === undefined) {
options.debug = options.dev
}
// Normalize ignore
options.ignore = options.ignore ? [].concat(options.ignore) : []
// Append ignorePrefix glob to ignore
if (typeof options.ignorePrefix === 'string') {
options.ignore.push(`**/${options.ignorePrefix}*.*`)
}
// Apply mode preset
let modePreset =
Options.modes[options.mode || 'universal'] || Options.modes['universal']
_.defaultsDeep(options, modePreset)
// If no server-side rendering, add appear true transition
/* istanbul ignore if */
if (options.render.ssr === false && options.transition) {
options.transition.appear = true
}
// We assume the SPA fallback path is 404.html (for GitHub Pages, Surge, etc.)
if (options.generate.fallback === true) {
options.generate.fallback = '404.html'
}
return options
}
Options.modes = {
universal: {
build: {
ssr: true
},
render: {
ssr: true
}
},
spa: {
build: {
ssr: false
},
render: {
ssr: false
}
}
}
// Options.unsafeKeys = [
// 'rootDir', 'srcDir', 'buildDir', 'modulesDir', 'cacheDir', 'nuxtDir',
// 'nuxtAppDir', 'build', 'generate', 'router.routes', 'appTemplatePath'
// ]
Options.defaults = {
mode: 'universal',
dev: process.env.NODE_ENV !== 'production',
debug: undefined, // Will be equal to dev if not provided
buildDir: '.nuxt',
cacheDir: '.cache',
nuxtDir: resolve(__dirname, '../..'),
nuxtAppDir: resolve(__dirname, '../app'),
modulesDir: ['node_modules'], // ~> relative to options.rootDir
ignorePrefix: '-',
ignore: [
'**/*.test.*'
],
extensions: [],
build: {
analyze: false,
profile: process.argv.includes('--profile'),
splitPages: true,
maxChunkSize: false,
extractCSS: false,
cssSourceMap: undefined,
ssr: undefined,
publicPath: '/_nuxt/',
filenames: {
app: '[name].[chunkhash].js',
chunk: '[name].[chunkhash].js',
css: '[name].[contenthash].css'
},
styleResources: {},
plugins: [],
babel: {
babelrc: false
},
postcss: {},
templates: [],
watch: [],
devMiddleware: {},
hotMiddleware: {},
stats: {
chunks: false,
children: false,
modules: false,
colors: true,
excludeAssets: [
/.map$/,
/index\..+\.html$/,
/vue-ssr-client-manifest.json/
]
}
},
generate: {
dir: 'dist',
routes: [],
concurrency: 500,
interval: 0,
subFolders: true,
fallback: '200.html',
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: false,
decodeEntities: true,
minifyCSS: true,
minifyJS: true,
processConditionalComments: true,
removeAttributeQuotes: false,
removeComments: false,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: false,
removeStyleLinkTypeAttributes: false,
removeTagWhitespace: false,
sortAttributes: true,
sortClassName: false,
trimCustomFragments: true,
useShortDoctype: true
}
},
env: {},
head: {
meta: [],
link: [],
style: [],
script: []
},
plugins: [],
css: [],
modules: [],
layouts: {},
serverMiddleware: [],
ErrorPage: null,
loading: {
color: 'black',
failedColor: 'red',
height: '2px',
duration: 5000,
rtl: false
},
loadingIndicator: {},
transition: {
name: 'page',
mode: 'out-in',
appear: false,
appearClass: 'appear',
appearActiveClass: 'appear-active',
appearToClass: 'appear-to'
},
layoutTransition: {
name: 'layout',
mode: 'out-in'
},
dir: {
assets: 'assets',
layouts: 'layouts',
middleware: 'middleware',
pages: 'pages',
static: 'static',
store: 'store'
},
router: {
mode: 'history',
base: '/',
routes: [],
middleware: [],
linkActiveClass: 'nuxt-link-active',
linkExactActiveClass: 'nuxt-link-exact-active',
extendRoutes: null,
scrollBehavior: null,
parseQuery: false,
stringifyQuery: false,
fallback: false
},
render: {
bundleRenderer: {},
resourceHints: true,
ssr: undefined,
http2: {
push: false,
shouldPush: null
},
static: {
prefix: true
},
gzip: {
threshold: 0
},
etag: {
weak: false
},
csp: {
enabled: false,
hashAlgorithm: 'sha256',
allowedSources: undefined,
policies: undefined
}
},
watchers: {
webpack: {},
chokidar: {}
},
editor: undefined,
hooks: null,
messages: {
error_404: 'This page could not be found',
server_error: 'Server error',
nuxtjs: 'Nuxt.js',
back_to_home: 'Back to the home page',
server_error_details:
'An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.',
client_error: 'Error',
client_error_details:
'An error occurred while rendering the page. Check developer tools console for details.'
}
}

165
lib/common/options.mjs Normal file
View File

@ -0,0 +1,165 @@
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
import Debug from 'debug'
import { isUrl, isPureObject } from '../common/utils'
import modes from './modes'
import defaults from './nuxt.config'
const debug = Debug('nuxt:build')
debug.color = 2 // Force green color
const Options = {}
export default Options
Options.from = function (_options) {
// Clone options to prevent unwanted side-effects
const options = Object.assign({}, _options)
// Normalize options
if (options.loading === true) {
delete options.loading
}
if (
options.router &&
options.router.middleware &&
!Array.isArray(options.router.middleware)
) {
options.router.middleware = [options.router.middleware]
}
if (options.router && typeof options.router.base === 'string') {
options._routerBaseSpecified = true
}
if (typeof options.transition === 'string') {
options.transition = { name: options.transition }
}
if (typeof options.layoutTransition === 'string') {
options.layoutTransition = { name: options.layoutTransition }
}
if (typeof options.extensions === 'string') {
options.extensions = [options.extensions]
}
const hasValue = v => typeof v === 'string' && v
options.rootDir = hasValue(options.rootDir) ? options.rootDir : process.cwd()
// Apply defaults by ${buildDir}/dist/build.config.js
// TODO: Unsafe operation.
// const buildDir = options.buildDir || defaults.buildDir
// const buildConfig = resolve(options.rootDir, buildDir, 'build.config.js')
// if (existsSync(buildConfig)) {
// _.defaultsDeep(options, require(buildConfig))
// }
// Apply defaults
_.defaultsDeep(options, defaults)
// Resolve dirs
options.srcDir = hasValue(options.srcDir)
? path.resolve(options.rootDir, options.srcDir)
: options.rootDir
options.buildDir = path.resolve(options.rootDir, options.buildDir)
options.cacheDir = path.resolve(options.rootDir, options.cacheDir)
// Populate modulesDir
options.modulesDir = []
.concat(options.modulesDir)
.concat(path.join(options.nuxtDir, 'node_modules'))
.filter(dir => hasValue(dir))
.map(dir => path.resolve(options.rootDir, dir))
// Sanitize extensions
if (options.extensions.indexOf('js') === -1) {
options.extensions.unshift('js')
}
if (options.extensions.indexOf('mjs') === -1) {
options.extensions.unshift('mjs')
}
// If app.html is defined, set the template path to the user template
options.appTemplatePath = path.resolve(options.buildDir, 'views/app.template.html')
if (fs.existsSync(path.join(options.srcDir, 'app.html'))) {
options.appTemplatePath = path.join(options.srcDir, 'app.html')
}
// Ignore publicPath on dev
/* istanbul ignore if */
if (options.dev && isUrl(options.build.publicPath)) {
options.build.publicPath = defaults.build.publicPath
}
// If store defined, update store options to true unless explicitly disabled
if (
options.store !== false &&
fs.existsSync(path.join(options.srcDir, options.dir.store)) &&
fs.readdirSync(path.join(options.srcDir, options.dir.store))
.find(filename => filename !== 'README.md' && filename[0] !== '.')
) {
options.store = true
}
// Normalize loadingIndicator
if (!isPureObject(options.loadingIndicator)) {
options.loadingIndicator = { name: options.loadingIndicator }
}
// Apply default hash to CSP option
if (options.render.csp === true) {
options.render.csp = { hashAlgorithm: 'sha256' }
}
// Apply defaults to loadingIndicator
options.loadingIndicator = Object.assign(
{
name: 'pulse',
color: '#dbe1ec',
background: 'white'
},
options.loadingIndicator
)
// cssSourceMap
if (options.build.cssSourceMap === undefined) {
options.build.cssSourceMap = options.dev
}
// babel cacheDirectory
if (options.build.babel.cacheDirectory === undefined) {
options.build.babel.cacheDirectory = options.dev
}
// Debug errors
if (options.debug === undefined) {
options.debug = options.dev
}
// Normalize ignore
options.ignore = options.ignore ? [].concat(options.ignore) : []
// Append ignorePrefix glob to ignore
if (typeof options.ignorePrefix === 'string') {
options.ignore.push(`**/${options.ignorePrefix}*.*`)
}
// Apply mode preset
const modePreset = modes[options.mode || 'universal'] || modes['universal']
_.defaultsDeep(options, modePreset)
// If no server-side rendering, add appear true transition
/* istanbul ignore if */
if (options.render.ssr === false && options.transition) {
options.transition.appear = true
}
// We assume the SPA fallback path is 404.html (for GitHub Pages, Surge, etc.)
if (options.generate.fallback === true) {
options.generate.fallback = '404.html'
}
return options
}

View File

@ -1,35 +1,32 @@
const { resolve, relative, sep } = require('path')
const _ = require('lodash')
const PrettyError = require('pretty-error')
const Chalk = require('chalk')
const ORA = require('ora')
import path from 'path'
import _ from 'lodash'
import Chalk from 'chalk'
import ORA from 'ora'
exports.pe = new PrettyError()
exports.printWarn = function (msg, from) {
export const printWarn = function (msg, from) {
/* eslint-disable no-console */
const fromStr = from ? Chalk.yellow(` ${from}\n\n`) : ' '
console.warn('\n' + Chalk.bgYellow.black(' WARN ') + fromStr + msg + '\n')
}
exports.renderError = function (_error, from) {
const errStr = exports.pe.render(_error)
export const renderError = function (_error, from) {
const errStr = _error.stack || String(_error)
const fromStr = from ? Chalk.red(` ${from}`) : ''
return '\n' + Chalk.bgRed.black(' ERROR ') + fromStr + '\n\n' + errStr
return '\n' + Chalk.bgRed.black(' ERROR ') + fromStr + ' ' + errStr
}
exports.printError = function () {
export const printError = function () {
/* eslint-disable no-console */
console.error(exports.renderError(...arguments))
console.error(renderError(...arguments))
}
exports.fatalError = function () {
export const fatalError = function () {
/* eslint-disable no-console */
console.error(exports.renderError(...arguments))
console.error(renderError(...arguments))
process.exit(1)
}
exports.createSpinner = function () {
export const createSpinner = function () {
return new ORA({
color: 'green',
spinner: 'clock',
@ -37,15 +34,15 @@ exports.createSpinner = function () {
})
}
exports.encodeHtml = function encodeHtml(str) {
export const encodeHtml = function encodeHtml(str) {
return str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
exports.getContext = function getContext(req, res) {
export const getContext = function getContext(req, res) {
return { req, res }
}
exports.setAnsiColors = function setAnsiColors(ansiHTML) {
export const setAnsiColors = function setAnsiColors(ansiHTML) {
ansiHTML.setColors({
reset: ['efefef', 'a6004c'],
darkgrey: '5a012b',
@ -58,7 +55,7 @@ exports.setAnsiColors = function setAnsiColors(ansiHTML) {
})
}
exports.waitFor = function waitFor(ms) {
export const waitFor = function waitFor(ms) {
return new Promise(resolve => setTimeout(resolve, ms || 0))
}
@ -76,9 +73,7 @@ async function promiseFinally(fn, finalFn) {
return result
}
exports.promiseFinally = promiseFinally
exports.timeout = function timeout(fn, ms, msg) {
export const timeout = function timeout(fn, ms, msg) {
let timerId
const warpPromise = promiseFinally(fn, () => clearTimeout(timerId))
const timerPromise = new Promise((resolve, reject) => {
@ -87,7 +82,7 @@ exports.timeout = function timeout(fn, ms, msg) {
return Promise.race([warpPromise, timerPromise])
}
exports.urlJoin = function urlJoin() {
export const urlJoin = function urlJoin() {
return [].slice
.call(arguments)
.join('/')
@ -95,11 +90,11 @@ exports.urlJoin = function urlJoin() {
.replace(':/', '://')
}
exports.isUrl = function isUrl(url) {
export const isUrl = function isUrl(url) {
return url.indexOf('http') === 0 || url.indexOf('//') === 0
}
exports.promisifyRoute = function promisifyRoute(fn, ...args) {
export const promisifyRoute = function promisifyRoute(fn, ...args) {
// If routes is an array
if (Array.isArray(fn)) {
return Promise.resolve(fn)
@ -125,18 +120,18 @@ exports.promisifyRoute = function promisifyRoute(fn, ...args) {
return promise
}
exports.sequence = function sequence(tasks, fn) {
export const sequence = function sequence(tasks, fn) {
return tasks.reduce(
(promise, task) => promise.then(() => fn(task)),
Promise.resolve()
)
}
exports.parallel = function parallel(tasks, fn) {
export const parallel = function parallel(tasks, fn) {
return Promise.all(tasks.map(task => fn(task)))
}
exports.chainFn = function chainFn(base, fn) {
export const chainFn = function chainFn(base, fn) {
/* istanbul ignore if */
if (!(fn instanceof Function)) {
return
@ -163,21 +158,21 @@ exports.chainFn = function chainFn(base, fn) {
}
}
exports.isPureObject = function isPureObject(o) {
export const isPureObject = function isPureObject(o) {
return !Array.isArray(o) && typeof o === 'object'
}
const isWindows = (exports.isWindows = /^win/.test(process.platform))
export const isWindows = /^win/.test(process.platform)
const wp = (exports.wp = function wp(p = '') {
export const wp = function wp(p = '') {
/* istanbul ignore if */
if (isWindows) {
return p.replace(/\\/g, '\\\\')
}
return p
})
}
exports.wChunk = function wChunk(p = '') {
export const wChunk = function wChunk(p = '') {
/* istanbul ignore if */
if (isWindows) {
return p.replace(/\//g, '_')
@ -186,10 +181,10 @@ exports.wChunk = function wChunk(p = '') {
}
const reqSep = /\//g
const sysSep = _.escapeRegExp(sep)
const sysSep = _.escapeRegExp(path.sep)
const normalize = string => string.replace(reqSep, sysSep)
const r = (exports.r = function r() {
export const r = function r() {
let args = Array.prototype.slice.apply(arguments)
let lastArg = _.last(args)
@ -197,44 +192,45 @@ const r = (exports.r = function r() {
return wp(lastArg)
}
return wp(resolve(...args.map(normalize)))
})
return wp(path.resolve(...args.map(normalize)))
}
exports.relativeTo = function relativeTo() {
export const relativeTo = function relativeTo() {
let args = Array.prototype.slice.apply(arguments)
let dir = args.shift()
// Resolve path
let path = r(...args)
let _path = r(...args)
// Check if path is an alias
if (path.indexOf('@') === 0 || path.indexOf('~') === 0) {
return path
if (_path.indexOf('@') === 0 || _path.indexOf('~') === 0) {
return _path
}
// Make correct relative path
let rp = relative(dir, path)
let rp = path.relative(dir, _path)
if (rp[0] !== '.') {
rp = './' + rp
}
return wp(rp)
}
exports.flatRoutes = function flatRoutes(router, path = '', routes = []) {
export const flatRoutes = function flatRoutes(router, _path = '', routes = []) {
router.forEach(r => {
if (!r.path.includes(':') && !r.path.includes('*')) {
/* istanbul ignore if */
if (r.children) {
if (path === '' && r.path === '/') {
if (_path === '' && r.path === '/') {
routes.push('/')
}
flatRoutes(r.children, path + r.path + '/', routes)
flatRoutes(r.children, _path + r.path + '/', routes)
} else {
path = path.replace(/^\/+$/, '/')
_path = _path.replace(/^\/+$/, '/')
routes.push(
(r.path === '' && path[path.length - 1] === '/'
? path.slice(0, -1)
: path) + r.path
(r.path === '' && _path[_path.length - 1] === '/'
? _path.slice(0, -1)
: _path) + r.path
)
}
}
@ -288,7 +284,7 @@ function cleanChildrenRoutes(routes, isChild = false) {
return routes
}
exports.createRoutes = function createRoutes(files, srcDir, pagesDir) {
export const createRoutes = function createRoutes(files, srcDir, pagesDir) {
let routes = []
files.forEach(file => {
let keys = file

View File

@ -1,12 +0,0 @@
const { Options, Utils } = require('../common')
const Module = require('./module')
const Nuxt = require('./nuxt')
const Renderer = require('./renderer')
module.exports = {
Nuxt,
Module,
Renderer,
Options,
Utils
}

9
lib/core/index.mjs Normal file
View File

@ -0,0 +1,9 @@
import Module from './module'
import Nuxt from './nuxt'
import Renderer from './renderer'
export default {
Nuxt,
Module,
Renderer
}

View File

@ -1,9 +1,9 @@
const Vue = require('vue')
const VueMeta = require('vue-meta')
const VueServerRenderer = require('vue-server-renderer')
const LRU = require('lru-cache')
import Vue from 'vue'
import VueMeta from 'vue-meta'
import VueServerRenderer from 'vue-server-renderer'
import LRU from 'lru-cache'
module.exports = class MetaRenderer {
export default class MetaRenderer {
constructor(nuxt, renderer) {
this.nuxt = nuxt
this.renderer = renderer

View File

@ -1,8 +1,9 @@
const Youch = require('@nuxtjs/youch')
const { join, resolve, relative, isAbsolute } = require('path')
const { readFile } = require('fs-extra')
import path from 'path'
module.exports = function errorMiddleware(err, req, res, next) {
import Youch from '@nuxtjs/youch'
import fs from 'fs-extra'
export default function errorMiddleware(err, req, res, next) {
// ensure statusCode, message and name fields
err.statusCode = err.statusCode || 500
err.message = err.message || 'Nuxt Server Error'
@ -83,20 +84,20 @@ async function readSource(frame) {
const searchPath = [
this.options.srcDir,
this.options.rootDir,
join(this.options.buildDir, 'dist'),
path.join(this.options.buildDir, 'dist'),
this.options.buildDir,
process.cwd()
]
// Scan filesystem for real source
for (let pathDir of searchPath) {
let fullPath = resolve(pathDir, frame.fileName)
let source = await readFile(fullPath, 'utf-8').catch(() => null)
let fullPath = path.resolve(pathDir, frame.fileName)
let source = await fs.readFile(fullPath, 'utf-8').catch(() => null)
if (source) {
frame.contents = source
frame.fullPath = fullPath
if (isAbsolute(frame.fileName)) {
frame.fileName = relative(this.options.rootDir, fullPath)
if (path.isAbsolute(frame.fileName)) {
frame.fileName = path.relative(this.options.rootDir, fullPath)
}
return
}

View File

@ -1,9 +1,9 @@
const generateETag = require('etag')
const fresh = require('fresh')
import generateETag from 'etag'
import fresh from 'fresh'
const { getContext } = require('../../common/utils')
import { getContext } from '../../common/utils'
module.exports = async function nuxtMiddleware(req, res, next) {
export default async function nuxtMiddleware(req, res, next) {
// Get context
const context = getContext(req, res)

View File

@ -1,9 +1,9 @@
const path = require('path')
const fs = require('fs')
const hash = require('hash-sum')
const { chainFn, sequence, printWarn } = require('../common/utils')
import path from 'path'
import fs from 'fs'
import hash from 'hash-sum'
import { chainFn, sequence, printWarn } from '../common/utils'
module.exports = class ModuleContainer {
export default class ModuleContainer {
constructor(nuxt) {
this.nuxt = nuxt
this.options = nuxt.options
@ -112,7 +112,7 @@ module.exports = class ModuleContainer {
// Resolve handler
if (!handler) {
handler = require(this.nuxt.resolvePath(src))
handler = this.nuxt.requireModule(src)
}
// Validate handler

View File

@ -1,20 +1,24 @@
const Debug = require('debug')
const enableDestroy = require('server-destroy')
const Module = require('module')
const { isPlainObject } = require('lodash')
const chalk = require('chalk')
const { existsSync } = require('fs-extra')
const { Options } = require('../common')
const { sequence, printError } = require('../common/utils')
const { resolve, join } = require('path')
const { version } = require('../../package.json')
const ModuleContainer = require('./module')
const Renderer = require('./renderer')
import Module from 'module'
import path from 'path'
import Debug from 'debug'
import enableDestroy from 'server-destroy'
import _ from 'lodash'
import chalk from 'chalk'
import fs from 'fs-extra'
import Options from '../common/options'
import { sequence, printError } from '../common/utils'
import packageJSON from '../../package.json'
import moduleUtil from '../common/module'
import ModuleContainer from './module'
import Renderer from './renderer'
const debug = Debug('nuxt:')
debug.color = 5
module.exports = class Nuxt {
export default class Nuxt {
constructor(options = {}) {
this.options = Options.from(options)
@ -41,7 +45,7 @@ module.exports = class Nuxt {
}
static get version() {
return version
return packageJSON.version
}
async ready() {
@ -50,7 +54,7 @@ module.exports = class Nuxt {
}
// Add hooks
if (isPlainObject(this.options.hooks)) {
if (_.isPlainObject(this.options.hooks)) {
this.addObjectHooks(this.options.hooks)
} else if (typeof this.options.hooks === 'function') {
this.options.hooks(this.hook)
@ -156,22 +160,22 @@ module.exports = class Nuxt {
})
}
resolveAlias(path) {
if (path.indexOf('@@') === 0 || path.indexOf('~~') === 0) {
return join(this.options.rootDir, path.substr(2))
resolveAlias(_path) {
if (_path.indexOf('@@') === 0 || _path.indexOf('~~') === 0) {
return path.join(this.options.rootDir, _path.substr(2))
}
if (path.indexOf('@') === 0 || path.indexOf('~') === 0) {
return join(this.options.srcDir, path.substr(1))
if (_path.indexOf('@') === 0 || _path.indexOf('~') === 0) {
return path.join(this.options.srcDir, _path.substr(1))
}
return resolve(this.options.srcDir, path)
return path.resolve(this.options.srcDir, _path)
}
resolvePath(path) {
resolvePath(_path) {
// Try to resolve using NPM resolve path first
try {
const resolvedPath = Module._resolveFilename(path, {
const resolvedPath = Module._resolveFilename(_path, {
paths: this.options.modulesDir
})
return resolvedPath
@ -181,19 +185,23 @@ module.exports = class Nuxt {
}
}
let _path = this.resolveAlias(path)
let __path = this.resolveAlias(_path)
if (existsSync(_path)) {
return _path
if (fs.existsSync(__path)) {
return __path
}
for (let ext of this.options.extensions) {
if (existsSync(_path + '.' + ext)) {
return _path + '.' + ext
if (fs.existsSync(__path + '.' + ext)) {
return __path + '.' + ext
}
}
throw new Error(`Cannot resolve "${path}" from "${_path}"`)
throw new Error(`Cannot resolve "${_path}" from "${__path}"`)
}
requireModule(name) {
return moduleUtil.requireModule(this.resolvePath(name))
}
async close(callback) {

View File

@ -1,22 +1,23 @@
const ansiHTML = require('ansi-html')
const serialize = require('serialize-javascript')
const serveStatic = require('serve-static')
const compression = require('compression')
const _ = require('lodash')
const { join, resolve } = require('path')
const fs = require('fs-extra')
const { createBundleRenderer } = require('vue-server-renderer')
const Debug = require('debug')
const connect = require('connect')
const launchMiddleware = require('launch-editor-middleware')
const crypto = require('crypto')
import path from 'path'
import crypto from 'crypto'
const { setAnsiColors, isUrl, waitFor, timeout } = require('../common/utils')
const { Options } = require('../common')
import ansiHTML from 'ansi-html'
import serialize from 'serialize-javascript'
import serveStatic from 'serve-static'
import compression from 'compression'
import _ from 'lodash'
import fs from 'fs-extra'
import vueServerRenderer from 'vue-server-renderer'
import Debug from 'debug'
import connect from 'connect'
import launchMiddleware from 'launch-editor-middleware'
const MetaRenderer = require('./meta')
const errorMiddleware = require('./middleware/error')
const nuxtMiddleware = require('./middleware/nuxt')
import { setAnsiColors, isUrl, waitFor, timeout } from '../common/utils'
import defaults from '../common/nuxt.config'
import MetaRenderer from './meta'
import errorMiddleware from './middleware/error'
import nuxtMiddleware from './middleware/nuxt'
const debug = Debug('nuxt:render')
debug.color = 4 // Force blue color
@ -25,7 +26,7 @@ setAnsiColors(ansiHTML)
let jsdom = null
module.exports = class Renderer {
export default class Renderer {
constructor(nuxt) {
this.nuxt = nuxt
this.options = nuxt.options
@ -66,18 +67,18 @@ module.exports = class Renderer {
}
async loadResources(_fs = fs) {
let distPath = resolve(this.options.buildDir, 'dist')
let distPath = path.resolve(this.options.buildDir, 'dist')
let updated = []
resourceMap.forEach(({ key, fileName, transform }) => {
let rawKey = '$$' + key
const path = join(distPath, fileName)
const _path = path.join(distPath, fileName)
let rawData, data
if (!_fs.existsSync(path)) {
if (!_fs.existsSync(_path)) {
return // Resource not exists
}
rawData = _fs.readFileSync(path, 'utf8')
rawData = _fs.readFileSync(_path, 'utf8')
if (!rawData || rawData === this.resources[rawKey]) {
return // No changes
}
@ -92,7 +93,7 @@ module.exports = class Renderer {
})
// Reload error template
const errorTemplatePath = resolve(this.options.buildDir, 'views/error.html')
const errorTemplatePath = path.resolve(this.options.buildDir, 'views/error.html')
if (fs.existsSync(errorTemplatePath)) {
this.resources.errorTemplate = parseTemplate(
fs.readFileSync(errorTemplatePath, 'utf8')
@ -100,7 +101,7 @@ module.exports = class Renderer {
}
// Load loading template
const loadingHTMLPath = resolve(this.options.buildDir, 'loading.html')
const loadingHTMLPath = path.resolve(this.options.buildDir, 'loading.html')
if (fs.existsSync(loadingHTMLPath)) {
this.resources.loadingHTML = fs.readFileSync(loadingHTMLPath, 'utf8')
this.resources.loadingHTML = this.resources.loadingHTML.replace(
@ -162,7 +163,7 @@ module.exports = class Renderer {
}
// Create bundle renderer for SSR
this.bundleRenderer = createBundleRenderer(
this.bundleRenderer = vueServerRenderer.createBundleRenderer(
this.resources.serverBundle,
Object.assign(
{
@ -180,12 +181,10 @@ module.exports = class Renderer {
const $m = m
let src
if (typeof m === 'string') {
src = this.nuxt.resolvePath(m)
m = require(src)
m = this.nuxt.requireModule(m)
}
if (typeof m.handler === 'string') {
src = this.nuxt.resolvePath(m.handler)
m.handler = require(src)
m.handler = this.nuxt.requireModule(m.handler)
}
const handler = m.handler || m
@ -204,7 +203,7 @@ module.exports = class Renderer {
get publicPath() {
return isUrl(this.options.build.publicPath)
? Options.defaults.build.publicPath
? defaults.build.publicPath
: this.options.build.publicPath
}
@ -250,7 +249,7 @@ module.exports = class Renderer {
// For serving static/ files to /
const staticMiddleware = serveStatic(
resolve(this.options.srcDir, this.options.dir.static),
path.resolve(this.options.srcDir, this.options.dir.static),
this.options.render.static
)
staticMiddleware.prefix = this.options.render.static.prefix
@ -259,7 +258,7 @@ module.exports = class Renderer {
// Serve .nuxt/dist/ files only for production
// For dev they will be served with devMiddleware
if (!this.options.dev) {
const distDir = resolve(this.options.buildDir, 'dist')
const distDir = path.resolve(this.options.buildDir, 'dist')
this.useMiddleware({
path: this.publicPath,
handler: serveStatic(distDir, {
@ -403,7 +402,7 @@ module.exports = class Renderer {
/* istanbul ignore if */
if (!jsdom) {
try {
jsdom = require('jsdom')
jsdom = this.nuxt.requireModule('jsdom')
} catch (e) /* istanbul ignore next */ {
/* eslint-disable no-console */
console.error('Fail when calling nuxt.renderAndGetWindow(url)')

View File

@ -1,11 +1,20 @@
/*!
* Nuxt.js
* (c) 2016-2017 Chopin Brothers
* Core maintainer: Pooya Parsa (@pi0)
* (c) 2016-2018 Chopin Brothers
* Core maintainers: Pooya Parsa (@pi0) - Clark Du (@clarkdo)
* Released under the MIT License.
*/
const core = require('./core')
const builder = require('./builder')
const requireModule = require('esm')(module, {})
module.exports = Object.assign({}, core, builder)
const core = requireModule('./core').default
const builder = requireModule('./builder').default
const Utils = requireModule('./common/utils')
const Options = requireModule('./common/options').default
module.exports = {
Utils,
Options,
...core,
...builder
}

Some files were not shown because too many files have changed in this diff Show More