From d9d5d1a5d865e53f5a259d213558f7b5666b7f76 Mon Sep 17 00:00:00 2001 From: Sebastien Chopin Date: Mon, 29 May 2017 17:24:40 +0200 Subject: [PATCH 01/24] Update TS example --- examples/typescript/index.d.ts | 19 ------------------- examples/typescript/modules/typescript.js | 12 ++++++------ examples/typescript/package.json | 4 ++-- 3 files changed, 8 insertions(+), 27 deletions(-) delete mode 100644 examples/typescript/index.d.ts diff --git a/examples/typescript/index.d.ts b/examples/typescript/index.d.ts deleted file mode 100644 index d4871b2cf0..0000000000 --- a/examples/typescript/index.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -//Deleting this file will cause "TS18003: No inputs were found in config file 'tsconfig.json'" - -//These declarations allow TypeScript to import non-js/ts files without the file extensions (such as .vue files) -declare module "~components/*" { -} - -declare module "~layouts/*" { -} - -declare module "~pages/*" { -} - -declare module "~assets/*" { - -} - -declare module "~static/*" { - -} diff --git a/examples/typescript/modules/typescript.js b/examples/typescript/modules/typescript.js index 9132f52892..efa5413d97 100644 --- a/examples/typescript/modules/typescript.js +++ b/examples/typescript/modules/typescript.js @@ -3,16 +3,16 @@ module.exports = function (options, next) { this.extendBuild((config) => { // Add TypeScript loader config.module.rules.push({ - test: /\.ts$/, - loader: 'ts-loader' + test: /\.ts$/, + loader: 'ts-loader' }) // Add TypeScript loader for vue files for (rule of config.module.rules) { - if (rule.loader === 'vue-loader') { - rule.query.loaders.ts = 'ts-loader?{"appendTsSuffixTo":["\\\\.vue$"]}' - } + if (rule.loader === 'vue-loader') { + rule.query.loaders.ts = 'ts-loader?{"appendTsSuffixTo":["\\\\.vue$"]}' + } } }) next() -} \ No newline at end of file +} diff --git a/examples/typescript/package.json b/examples/typescript/package.json index 6d5a5cdd9d..17973f83f6 100644 --- a/examples/typescript/package.json +++ b/examples/typescript/package.json @@ -4,7 +4,7 @@ "dependencies": { "axios": "^0.16.1", "gsap": "^1.19.1", - "nuxt": "latest", + "nuxt": "^1.0.0-alpha2", "nuxt-class-component": "^1.0.1", "tachyons": "^4.7.0", "vue-class-component": "^5.0.1", @@ -21,4 +21,4 @@ "ts-loader": "^2.0.3", "typescript": "^2.2.2" } -} \ No newline at end of file +} From 4f1e82e959101c11fdcaada11f33420245ffdea4 Mon Sep 17 00:00:00 2001 From: Sebastien Chopin Date: Tue, 30 May 2017 12:00:31 +0200 Subject: [PATCH 02/24] fix: payload is not fully working on nuxt generate --- lib/app/utils.js | 2 +- lib/generate.js | 26 ++++++++++++++++--------- test/basic.generate.test.js | 4 ++-- test/fixtures/basic/nuxt.config.js | 2 +- test/fixtures/basic/pages/users/_id.vue | 3 ++- 5 files changed, 23 insertions(+), 14 deletions(-) diff --git a/lib/app/utils.js b/lib/app/utils.js index 9b88a3a79f..048d3e9be0 100644 --- a/lib/app/utils.js +++ b/lib/app/utils.js @@ -61,7 +61,7 @@ export function getContext (context, app) { app: app, <%= (store ? 'store: context.store,' : '') %> route: (context.to ? context.to : context.route), - payload : context.payload, + payload: context.payload, error: context.error, base: '<%= router.base %>', env: <%= JSON.stringify(env) %> diff --git a/lib/generate.js b/lib/generate.js index cd780a2492..65de915b46 100644 --- a/lib/generate.js +++ b/lib/generate.js @@ -80,14 +80,21 @@ export default async function () { } } function decorateWithPayloads (routes) { - let routeMap = _(routes).map((route) => { - return [route, {route, payload: {}}] - }).fromPairs().value() + let routeMap = {} + // Fill routeMap for known routes + routes.forEach((route) => { + routeMap[route] = { + route, + payload: null + } + }) + // Fill routeMap with given generate.routes generateRoutes.forEach((route) => { - // route argument is either a string or like {route : "/my_route/1"} - route = _.isString(route) ? route : route.route - if (!routeMap[route]) { - routeMap[route] = {route, payload: route.payload} + // route is either a string or like {route : "/my_route/1"} + const path = _.isString(route) ? route : route.route + routeMap[path] = { + route: path, + payload: route.payload || null } }) return _.values(routeMap) @@ -95,7 +102,8 @@ export default async function () { /* ** Generate only index.html for router.mode = 'hash' */ - let routes = (this.options.router.mode === 'hash') ? [{route: '/'}] : decorateWithPayloads(this.routes) + let routes = (this.options.router.mode === 'hash') ? ['/'] : this.routes + routes = decorateWithPayloads(routes) while (routes.length) { let n = 0 @@ -110,7 +118,7 @@ export default async function () { } } catch (err) { /* istanbul ignore next */ - errors.push({ type: 'unhandled', route, error: err }) + return errors.push({ type: 'unhandled', route, error: err }) } if (this.options.generate.minify) { try { diff --git a/test/basic.generate.test.js b/test/basic.generate.test.js index 254dc1453e..02855fb73a 100644 --- a/test/basic.generate.test.js +++ b/test/basic.generate.test.js @@ -74,9 +74,9 @@ test('/users/2', async t => { t.true(html.includes('

User: 2

')) }) -test('/users/3', async t => { +test('/users/3 (payload given)', async t => { const html = await rp(url('/users/3')) - t.true(html.includes('

User: 3

')) + t.true(html.includes('

User: 3000

')) }) test('/users/4 -> Not found', async t => { diff --git a/test/fixtures/basic/nuxt.config.js b/test/fixtures/basic/nuxt.config.js index d6ba223b68..fb6e6734c7 100644 --- a/test/fixtures/basic/nuxt.config.js +++ b/test/fixtures/basic/nuxt.config.js @@ -3,7 +3,7 @@ module.exports = { routes: [ '/users/1', '/users/2', - '/users/3' + { route: '/users/3', payload: { id: 3000 } } ], interval: 200 } diff --git a/test/fixtures/basic/pages/users/_id.vue b/test/fixtures/basic/pages/users/_id.vue index 8cd8e0f0d1..ed71a446ec 100644 --- a/test/fixtures/basic/pages/users/_id.vue +++ b/test/fixtures/basic/pages/users/_id.vue @@ -4,7 +4,8 @@ diff --git a/test/with-config.test.js b/test/with-config.test.js index bbce95a138..0e40937b32 100644 --- a/test/with-config.test.js +++ b/test/with-config.test.js @@ -78,7 +78,7 @@ test('/test/error', async t => { test('/test/user-agent', async t => { const window = await nuxt.renderAndGetWindow(url('/test/user-agent')) const html = window.document.body.innerHTML - t.true(html.includes('
Node.js'))
+  t.true(html.includes('
Mozilla'))
 })
 
 test('/test/about-bis (added with extendRoutes)', async t => {

From e967191167665c49bd7221799fded2d8e5d9541a Mon Sep 17 00:00:00 2001
From: Sebastien Chopin 
Date: Wed, 31 May 2017 10:22:04 +0200
Subject: [PATCH 09/24] Fix types to link to .ts file

---
 package.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/package.json b/package.json
index 8b8567e5fc..ec97f4e412 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,7 @@
     }
   ],
   "main": "./index.js",
-  "types": "./index.d.js",
+  "types": "./index.d.ts",
   "license": "MIT",
   "repository": {
     "type": "git",

From f089bcfff628f7c9b311e2745efa68bcf9a9a1ca Mon Sep 17 00:00:00 2001
From: Sebastien Chopin 
Date: Wed, 31 May 2017 13:21:24 +0200
Subject: [PATCH 10/24] Add hotReload in context

---
 lib/app/client.js | 2 +-
 lib/app/utils.js  | 3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/lib/app/client.js b/lib/app/client.js
index 5b92f79b8c..ccb2381d02 100644
--- a/lib/app/client.js
+++ b/lib/app/client.js
@@ -270,7 +270,7 @@ function addHotReload ($component, depth) {
       <%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
       router.push(path)
     }
-    let context = getContext({ route: router.currentRoute<%= (store ? ', store' : '') %>, isClient: true, next: next.bind(this), error: this.error }, app)
+    let context = getContext({ route: router.currentRoute<%= (store ? ', store' : '') %>, isClient: true, hotReload: true, next: next.bind(this), error: this.error }, app)
     <%= (loading ? 'this.$loading.start && this.$loading.start()' : '') %>
     callMiddleware.call(this, Components, context)
     .then(() => {
diff --git a/lib/app/utils.js b/lib/app/utils.js
index 048d3e9be0..edd88defb2 100644
--- a/lib/app/utils.js
+++ b/lib/app/utils.js
@@ -64,7 +64,8 @@ export function getContext (context, app) {
     payload: context.payload,
     error: context.error,
     base: '<%= router.base %>',
-    env: <%= JSON.stringify(env) %>
+    env: <%= JSON.stringify(env) %>,
+    hotReload: context.hotReload || false
   }
   const next = context.next
   ctx.params = ctx.route.params || {}

From 43de27faef96e543b07db6c58991107e71fe8743 Mon Sep 17 00:00:00 2001
From: Sebastien Chopin 
Date: Wed, 31 May 2017 13:21:55 +0200
Subject: [PATCH 11/24] Fix i18n example for alpha3

---
 examples/i18n/layouts/default.vue | 2 +-
 examples/i18n/middleware/i18n.js  | 7 +++++--
 examples/i18n/package.json        | 2 +-
 examples/i18n/plugins/i18n.js     | 7 +------
 4 files changed, 8 insertions(+), 10 deletions(-)

diff --git a/examples/i18n/layouts/default.vue b/examples/i18n/layouts/default.vue
index 09cdd6ddea..ccfcbd8123 100644
--- a/examples/i18n/layouts/default.vue
+++ b/examples/i18n/layouts/default.vue
@@ -7,7 +7,7 @@
           
             {{ $t('links.home') }}
           
-          
+          
             {{ $t('links.about') }}
           
           
diff --git a/examples/i18n/middleware/i18n.js b/examples/i18n/middleware/i18n.js
index b04fb950a3..c787ca808a 100644
--- a/examples/i18n/middleware/i18n.js
+++ b/examples/i18n/middleware/i18n.js
@@ -1,4 +1,7 @@
-export default function ({ app, store, route, params, error, redirect }) {
+export default function ({ app, store, route, params, error, redirect, hotReload }) {
+  // Check if middleware called from hot-reloading, ignore
+  if (hotReload) return
+  // Get locale from params
   const locale = params.lang || 'en'
   if (store.state.locales.indexOf(locale) === -1) {
     return error({ message: 'This page could not be found.', statusCode: 404 })
@@ -8,6 +11,6 @@ export default function ({ app, store, route, params, error, redirect }) {
   app.i18n.locale = store.state.locale
   // If route is /en/... -> redirect to /...
   if (locale === 'en' && route.fullPath.indexOf('/en') === 0) {
-    redirect(route.fullPath.replace(/^\/en/, '/'))
+    return redirect(route.fullPath.replace(/^\/en/, '/'))
   }
 }
diff --git a/examples/i18n/package.json b/examples/i18n/package.json
index 8668f2c65a..5dd206d014 100644
--- a/examples/i18n/package.json
+++ b/examples/i18n/package.json
@@ -2,7 +2,7 @@
   "name": "nuxt-i18n",
   "dependencies": {
     "nuxt": "latest",
-    "vue-i18n": "^6.0.0"
+    "vue-i18n": "^7.0.0"
   },
   "scripts": {
     "dev": "nuxt",
diff --git a/examples/i18n/plugins/i18n.js b/examples/i18n/plugins/i18n.js
index 02e20adf74..e4859aadc9 100644
--- a/examples/i18n/plugins/i18n.js
+++ b/examples/i18n/plugins/i18n.js
@@ -3,12 +3,7 @@ import VueI18n from 'vue-i18n'
 
 Vue.use(VueI18n)
 
-export default ({ isClient, app, store, route, error, redirect }) => {
-  console.log(route.path)
-  if (isClient && route.path === '/fr/about') {
-    return redirect('/about')
-  }
-  console.log(error)
+export default ({ app, store }) => {
   // Set i18n instance on app
   // This way we can use it in middleware and pages asyncData/fetch
   app.i18n = new VueI18n({

From 3de7921b5a53e288d24c500b71507756853cc4c4 Mon Sep 17 00:00:00 2001
From: Pooya Parsa 
Date: Wed, 31 May 2017 17:24:36 +0430
Subject: [PATCH 12/24] test: fix appveyor

---
 test/module.test.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/test/module.test.js b/test/module.test.js
index d03cce264f..31b5bc7cac 100755
--- a/test/module.test.js
+++ b/test/module.test.js
@@ -26,7 +26,7 @@ test('Vendor', async t => {
 })
 
 test('Plugin', async t => {
-  t.true(nuxt.options.plugins[0].src.includes('fixtures/module/.nuxt/basic.reverse.'), 'plugin added to config')
+  t.true(nuxt.options.plugins[0].src.includes('~/.nuxt/basic.reverse.'), 'plugin added to config')
   const { html } = await nuxt.renderRoute('/')
   t.true(html.includes('

TXUN

'), 'plugin works') }) From d161a5785cf6574ee4b307360eacc6a206619dba Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 31 May 2017 17:36:23 +0430 Subject: [PATCH 13/24] test: fix appveyor part 2! --- test/module.test.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/module.test.js b/test/module.test.js index 31b5bc7cac..c617228e5c 100755 --- a/test/module.test.js +++ b/test/module.test.js @@ -8,6 +8,8 @@ const url = (route) => 'http://localhost:' + port + route let nuxt = null let server = null +const wp = p => /^win/.test(process.platform) ? p.replace(/[\\/]/g, '\\\\') : p + // Init nuxt.js and create server listening on localhost:4000 test.before('Init Nuxt.js', async t => { const Nuxt = require('../') @@ -26,7 +28,7 @@ test('Vendor', async t => { }) test('Plugin', async t => { - t.true(nuxt.options.plugins[0].src.includes('~/.nuxt/basic.reverse.'), 'plugin added to config') + t.true(nuxt.options.plugins[0].src.includes(wp('fixtures/module/.nuxt/basic.reverse.')), 'plugin added to config') const { html } = await nuxt.renderRoute('/') t.true(html.includes('

TXUN

'), 'plugin works') }) From 9f7722f84539d67910a5b85562dff4a45cdd14d7 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 31 May 2017 17:36:37 +0430 Subject: [PATCH 14/24] test: add node 8 to build matrix --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 7db39d1a44..c2a14e7f60 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ language: node_js node_js: + - "8.0" - "7.2" - "6.9" before_install: From c5ca8c64f18d29b83137399b2aa5f6164f53b3c6 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 31 May 2017 18:51:16 +0430 Subject: [PATCH 15/24] refactor: nuxt constructor no longer returns a promise by not returning a promise we can expose .render method also the old way of using nuxt won't change by 1.x release --- bin/nuxt-build | 19 +++++------ bin/nuxt-dev | 51 ++++++++++++++-------------- bin/nuxt-generate | 19 +++++------ bin/nuxt-start | 11 +++--- examples/with-ava/test/index.test.js | 2 +- lib/build.js | 4 ++- lib/module.js | 37 +++++++++++++------- lib/nuxt.js | 8 ----- test/basic.dev.test.js | 2 +- test/basic.fail.generate.test.js | 2 +- test/basic.generate.test.js | 2 +- test/basic.test.js | 2 +- test/children.test.js | 2 +- test/dynamic-routes.test.js | 2 +- test/error.test.js | 2 +- test/index.test.js | 8 ++--- test/module.test.js | 2 +- test/utils.test.js | 2 +- test/with-config.test.js | 4 +-- 19 files changed, 92 insertions(+), 89 deletions(-) diff --git a/bin/nuxt-build b/bin/nuxt-build index c85d1b6fed..1af998d2be 100755 --- a/bin/nuxt-build +++ b/bin/nuxt-build @@ -52,13 +52,12 @@ if (analyzeBuild) { } console.log('[nuxt] Building...') // eslint-disable-line no-console -new Nuxt(options).then(nuxt => { - nuxt.build() - .then(() => { - console.log('[nuxt] Building done') // eslint-disable-line no-console - }) - .catch((err) => { - console.error(err) // eslint-disable-line no-console - process.exit(1) - }) -}) +var nuxt = module.exports = new Nuxt(options) +nuxt.build() + .then(() => { + console.log('[nuxt] Building done') // eslint-disable-line no-console + }) + .catch((err) => { + console.error(err) // eslint-disable-line no-console + process.exit(1) + }) diff --git a/bin/nuxt-dev b/bin/nuxt-dev index 351a82a680..7b2a36bda2 100755 --- a/bin/nuxt-dev +++ b/bin/nuxt-dev @@ -39,19 +39,20 @@ if (typeof options.rootDir !== 'string') { } options.dev = true // Add hot reloading and watching changes -new Nuxt(options).then(nuxt => { - var server = new nuxt.Server(nuxt) - .listen(process.env.PORT || process.env.npm_package_config_nuxt_port, process.env.HOST || process.env.npm_package_config_nuxt_host) - listenOnConfigChanges(nuxt, server) +var nuxt = module.exports = new Nuxt(options) +var port = process.env.PORT || process.env.npm_package_config_nuxt_port +var host = process.env.HOST || process.env.npm_package_config_nuxt_host +var server = nuxt.server = new nuxt.Server(nuxt).listen(port, host) - nuxt.build() - .catch((err) => { - console.error(err) // eslint-disable-line no-console - process.exit(1) - }) -}) +listenOnConfigChanges(nuxt, server) -function listenOnConfigChanges (nuxt, server) { +nuxt.build() + .catch((err) => { + console.error(err) // eslint-disable-line no-console + process.exit(1) + }) + +function listenOnConfigChanges(nuxt, server) { // Listen on nuxt.config.js changes var build = _.debounce(() => { debug('[nuxt.config.js] changed') @@ -66,20 +67,20 @@ function listenOnConfigChanges (nuxt, server) { } options.rootDir = rootDir nuxt.close() - .then(() => { - nuxt.renderer = null - debug('Rebuilding the app...') - return (new Nuxt(options)).then(nuxt => nuxt.build()) - }) - .then((nuxt) => { - server.nuxt = nuxt - }) - .catch((error) => { - console.error('Error while rebuild the app:', error) // eslint-disable-line no-console - process.exit(1) - }) + .then(() => { + nuxt.renderer = null + debug('Rebuilding the app...') + return new Nuxt(options).build() + }) + .then((nuxt) => { + server.nuxt = nuxt + }) + .catch((error) => { + console.error('Error while rebuild the app:', error) // eslint-disable-line no-console + process.exit(1) + }) }, 200) var nuxtConfigFile = resolve(rootDir, nuxtConfigFileName) - chokidar.watch(nuxtConfigFile, Object.assign({}, nuxt.options.watchers.chokidar, { ignoreInitial: true })) - .on('all', build) + chokidar.watch(nuxtConfigFile, Object.assign({}, nuxt.options.watchers.chokidar, {ignoreInitial: true})) + .on('all', build) } diff --git a/bin/nuxt-generate b/bin/nuxt-generate index 8d085b666c..c187810fa1 100755 --- a/bin/nuxt-generate +++ b/bin/nuxt-generate @@ -20,13 +20,12 @@ if (typeof options.rootDir !== 'string') { options.dev = false // Force production mode (no webpack middleware called) console.log('[nuxt] Generating...') // eslint-disable-line no-console -new Nuxt(options).then(nuxt => { - nuxt.generate() - .then(() => { - console.log('[nuxt] Generate done') // eslint-disable-line no-console - }) - .catch((err) => { - console.error(err) // eslint-disable-line no-console - process.exit(1) - }) -}) +var nuxt = module.exports = new Nuxt(options) +nuxt.generate() + .then(() => { + console.log('[nuxt] Generate done') // eslint-disable-line no-console + }) + .catch((err) => { + console.error(err) // eslint-disable-line no-console + process.exit(1) + }) diff --git a/bin/nuxt-start b/bin/nuxt-start index f39daf9b19..8af26fbaf4 100755 --- a/bin/nuxt-start +++ b/bin/nuxt-start @@ -16,10 +16,7 @@ if (typeof options.rootDir !== 'string') { } options.dev = false // Force production mode (no webpack middleware called) -new Nuxt(options).then(nuxt => { - new nuxt.Server(nuxt) - .listen( - process.env.PORT || process.env.npm_package_config_nuxt_port, - process.env.HOST || process.env.npm_package_config_nuxt_host - ) -}) +var nuxt = module.exports = new Nuxt(options) +var port = process.env.PORT || process.env.npm_package_config_nuxt_port +var host = process.env.HOST || process.env.npm_package_config_nuxt_host +var server = nuxt.server = new nuxt.Server(nuxt).listen(port, host) diff --git a/examples/with-ava/test/index.test.js b/examples/with-ava/test/index.test.js index e5249406f1..21c25e9320 100755 --- a/examples/with-ava/test/index.test.js +++ b/examples/with-ava/test/index.test.js @@ -14,7 +14,7 @@ test.before('Init Nuxt.js', async t => { try { config = require(resolve(rootDir, 'nuxt.config.js')) } catch (e) {} config.rootDir = rootDir // project folder config.dev = false // production build - nuxt = await new Nuxt(config) + nuxt = new Nuxt(config) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(4000, 'localhost') diff --git a/lib/build.js b/lib/build.js index f548c28d75..a5793131a3 100644 --- a/lib/build.js +++ b/lib/build.js @@ -97,8 +97,10 @@ export function options () { } export async function build () { - this._nuxtPages = typeof this.createRoutes !== 'function' + // Initialize modules first + await this.module.init() // Check if pages dir exists and warn if not + this._nuxtPages = typeof this.createRoutes !== 'function' if (this._nuxtPages) { if (!fs.existsSync(join(this.srcDir, 'pages'))) { if (fs.existsSync(join(this.srcDir, '..', 'pages'))) { diff --git a/lib/module.js b/lib/module.js index 4bd726d085..17f73a2edd 100755 --- a/lib/module.js +++ b/lib/module.js @@ -4,16 +4,30 @@ import path from 'path' import fs from 'fs' import {uniq} from 'lodash' import hash from 'hash-sum' -import {chainFn} from './utils' +import {chainFn, sequence} from './utils' + +const debug = require('debug')('nuxt:module') class Module { - constructor (nuxt) { + constructor(nuxt) { this.nuxt = nuxt this.options = nuxt.options this.modules = [] + this.initialized = false } - addVendor (vendor) { + async init() { + if (this.initialized) { + debug('[nuxt] Modules are already initialized') + return + } + // Install all modules in sequence + await sequence(this.options.modules, this.addModule.bind(this)) + // Indicate modules are already initialized + this.initialized = true + } + + addVendor(vendor) { /* istanbul ignore if */ if (!vendor) { return @@ -21,7 +35,7 @@ class Module { this.options.build.vendor = uniq(this.options.build.vendor.concat(vendor)) } - addTemplate (template) { + addTemplate(template) { /* istanbul ignore if */ if (!template) { return @@ -31,8 +45,7 @@ class Module { const srcPath = path.parse(src) /* istanbul ignore if */ if (!src || typeof src !== 'string' || !fs.existsSync(src)) { - // eslint-disable-next-line no-console - console.warn('[nuxt] invalid template', template) + debug('[nuxt] invalid template', template) return } // Generate unique and human readable dst filename @@ -48,7 +61,7 @@ class Module { return templateObj } - addPlugin (template) { + addPlugin(template) { const {dst} = this.addTemplate(template) // Add to nuxt plugins this.options.plugins.push({ @@ -57,19 +70,19 @@ class Module { }) } - addServerMiddleware (middleware) { + addServerMiddleware(middleware) { this.options.serverMiddleware.push(middleware) } - extendBuild (fn) { + extendBuild(fn) { this.options.build.extend = chainFn(this.options.build.extend, fn) } - extendRoutes (fn) { + extendRoutes(fn) { this.options.router.extendRoutes = chainFn(this.options.router.extendRoutes, fn) } - requireModule (moduleOpts) { + requireModule(moduleOpts) { if (this.modules.indexOf(moduleOpts) !== -1 || this.modules.indexOf(moduleOpts.src) !== -1) { return false } @@ -77,7 +90,7 @@ class Module { return this.addModule(moduleOpts) } - addModule (moduleOpts) { + addModule(moduleOpts) { /* istanbul ignore if */ if (!moduleOpts) { return diff --git a/lib/nuxt.js b/lib/nuxt.js index 64fb633b1b..c045e483c2 100644 --- a/lib/nuxt.js +++ b/lib/nuxt.js @@ -121,14 +121,6 @@ class Nuxt { this.utils = utils // Add module integration this.module = new Module(this) - // Install all modules in sequence and then return `this` instance - return utils.sequence(options.modules, this.module.addModule.bind(this.module)) - .then(() => this) - .catch(/* istanbul ignore next */ (err) => { - console.error('[nuxt] error while initializing modules') // eslint-disable-line no-console - console.error(err) // eslint-disable-line no-console - process.exit(1) - }) } close (callback) { diff --git a/test/basic.dev.test.js b/test/basic.dev.test.js index 9d1f02f968..42e60e22fa 100644 --- a/test/basic.dev.test.js +++ b/test/basic.dev.test.js @@ -14,7 +14,7 @@ test.before('Init Nuxt.js', async t => { rootDir: resolve(__dirname, 'fixtures/basic'), dev: true } - nuxt = await new Nuxt(options) + nuxt = new Nuxt(options) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(port, 'localhost') diff --git a/test/basic.fail.generate.test.js b/test/basic.fail.generate.test.js index b96a8b343d..c1c85a30fa 100644 --- a/test/basic.fail.generate.test.js +++ b/test/basic.fail.generate.test.js @@ -14,7 +14,7 @@ test('Fail with routes() which throw an error', async t => { } } } - const nuxt = await new Nuxt(options) + const nuxt = new Nuxt(options) return new Promise((resolve) => { var oldExit = process.exit var oldCE = console.error // eslint-disable-line no-console diff --git a/test/basic.generate.test.js b/test/basic.generate.test.js index 02855fb73a..cc0c160912 100644 --- a/test/basic.generate.test.js +++ b/test/basic.generate.test.js @@ -17,7 +17,7 @@ test.before('Init Nuxt.js', async t => { let config = require(resolve(rootDir, 'nuxt.config.js')) config.rootDir = rootDir config.dev = false - nuxt = await new Nuxt(config) + nuxt = new Nuxt(config) try { await nuxt.generate() // throw an error (of /validate route) } catch (err) {} diff --git a/test/basic.test.js b/test/basic.test.js index 514ccf39c0..14a63aaa5b 100755 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -16,7 +16,7 @@ test.before('Init Nuxt.js', async t => { rootDir: resolve(__dirname, 'fixtures/basic'), dev: false } - nuxt = await new Nuxt(options) + nuxt = new Nuxt(options) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(port, 'localhost') diff --git a/test/children.test.js b/test/children.test.js index 261b878380..2536ed4e22 100644 --- a/test/children.test.js +++ b/test/children.test.js @@ -13,7 +13,7 @@ test.before('Init Nuxt.js', async t => { rootDir: resolve(__dirname, 'fixtures/children'), dev: false } - nuxt = await new Nuxt(options) + nuxt = new Nuxt(options) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(port, 'localhost') diff --git a/test/dynamic-routes.test.js b/test/dynamic-routes.test.js index 126d433f88..40bd5446d2 100644 --- a/test/dynamic-routes.test.js +++ b/test/dynamic-routes.test.js @@ -6,7 +6,7 @@ const readFile = pify(fs.readFile) test.before('Init Nuxt.js', async t => { const Nuxt = require('../') - const nuxt = await new Nuxt({ + const nuxt = new Nuxt({ rootDir: resolve(__dirname, 'fixtures/dynamic-routes'), dev: false }) diff --git a/test/error.test.js b/test/error.test.js index 709b37b347..26fba45f6e 100644 --- a/test/error.test.js +++ b/test/error.test.js @@ -13,7 +13,7 @@ test.before('Init Nuxt.js', async t => { rootDir: resolve(__dirname, 'fixtures/error'), dev: false } - nuxt = await new Nuxt(options) + nuxt = new Nuxt(options) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(port, 'localhost') diff --git a/test/index.test.js b/test/index.test.js index 40be484e4a..53f05b9afa 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -8,7 +8,7 @@ test('Nuxt.js Class', t => { }) test('Nuxt.js Instance', async t => { - const nuxt = await new Nuxt() + const nuxt = new Nuxt() t.is(typeof nuxt, 'object') t.is(nuxt.dev, true) t.is(typeof nuxt.build, 'function') @@ -16,7 +16,7 @@ test('Nuxt.js Instance', async t => { }) test.serial('Fail when build not done and try to render', async t => { - const nuxt = await new Nuxt({ + const nuxt = new Nuxt({ dev: false, rootDir: resolve(__dirname, 'fixtures/empty') }) @@ -37,7 +37,7 @@ test.serial('Fail when build not done and try to render', async t => { }) test.serial('Fail to build when no pages/ directory but is in the parent', async t => { - const nuxt = await new Nuxt({ + const nuxt = new Nuxt({ dev: false, rootDir: resolve(__dirname, 'fixtures', 'empty', 'pages') }) @@ -58,7 +58,7 @@ test.serial('Fail to build when no pages/ directory but is in the parent', async }) test.serial('Fail to build when no pages/ directory', async t => { - const nuxt = await new Nuxt({ + const nuxt = new Nuxt({ dev: false, rootDir: resolve(__dirname) }) diff --git a/test/module.test.js b/test/module.test.js index c617228e5c..58e15de574 100755 --- a/test/module.test.js +++ b/test/module.test.js @@ -17,7 +17,7 @@ test.before('Init Nuxt.js', async t => { let config = require(resolve(rootDir, 'nuxt.config.js')) config.rootDir = rootDir config.dev = false - nuxt = await new Nuxt(config) + nuxt = new Nuxt(config) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(port, 'localhost') diff --git a/test/utils.test.js b/test/utils.test.js index 052db5a900..3a2aff00ff 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -5,7 +5,7 @@ let utils // Init nuxt.js and create server listening on localhost:4000 test.before('Init Nuxt.js', async t => { const Nuxt = require('../') - let nuxt = await new Nuxt({ dev: false }) + let nuxt = new Nuxt({ dev: false }) utils = nuxt.utils }) diff --git a/test/with-config.test.js b/test/with-config.test.js index 0e40937b32..07c299f245 100644 --- a/test/with-config.test.js +++ b/test/with-config.test.js @@ -15,7 +15,7 @@ test.before('Init Nuxt.js', async t => { let config = require(resolve(rootDir, 'nuxt.config.js')) config.rootDir = rootDir config.dev = false - nuxt = await new Nuxt(config) + nuxt = new Nuxt(config) await nuxt.build() server = new nuxt.Server(nuxt) server.listen(port, 'localhost') @@ -110,5 +110,5 @@ test.after('Should be able to start Nuxt with build done', async t => { let config = require(resolve(rootDir, 'nuxt.config.js')) config.rootDir = rootDir config.dev = false - nuxt = await new Nuxt(config) + nuxt = new Nuxt(config) }) From 79b97093d064cf2397c69c77ec37e4df4ba42684 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 31 May 2017 18:56:49 +0430 Subject: [PATCH 16/24] ESLint --- lib/module.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/module.js b/lib/module.js index 17f73a2edd..8c502e072b 100755 --- a/lib/module.js +++ b/lib/module.js @@ -9,14 +9,14 @@ import {chainFn, sequence} from './utils' const debug = require('debug')('nuxt:module') class Module { - constructor(nuxt) { + constructor (nuxt) { this.nuxt = nuxt this.options = nuxt.options this.modules = [] this.initialized = false } - async init() { + async init () { if (this.initialized) { debug('[nuxt] Modules are already initialized') return @@ -27,7 +27,7 @@ class Module { this.initialized = true } - addVendor(vendor) { + addVendor (vendor) { /* istanbul ignore if */ if (!vendor) { return @@ -35,7 +35,7 @@ class Module { this.options.build.vendor = uniq(this.options.build.vendor.concat(vendor)) } - addTemplate(template) { + addTemplate (template) { /* istanbul ignore if */ if (!template) { return @@ -61,7 +61,7 @@ class Module { return templateObj } - addPlugin(template) { + addPlugin (template) { const {dst} = this.addTemplate(template) // Add to nuxt plugins this.options.plugins.push({ @@ -70,19 +70,19 @@ class Module { }) } - addServerMiddleware(middleware) { + addServerMiddleware (middleware) { this.options.serverMiddleware.push(middleware) } - extendBuild(fn) { + extendBuild (fn) { this.options.build.extend = chainFn(this.options.build.extend, fn) } - extendRoutes(fn) { + extendRoutes (fn) { this.options.router.extendRoutes = chainFn(this.options.router.extendRoutes, fn) } - requireModule(moduleOpts) { + requireModule (moduleOpts) { if (this.modules.indexOf(moduleOpts) !== -1 || this.modules.indexOf(moduleOpts.src) !== -1) { return false } @@ -90,7 +90,7 @@ class Module { return this.addModule(moduleOpts) } - addModule(moduleOpts) { + addModule (moduleOpts) { /* istanbul ignore if */ if (!moduleOpts) { return From 44c6a2524772a8c36a9e208d4ce576e8badf7f6b Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 31 May 2017 19:24:53 +0430 Subject: [PATCH 17/24] feat(module): easier options Allow using babel style array and flatten options --- lib/module.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/module.js b/lib/module.js index 8c502e072b..2f54eb6ab5 100755 --- a/lib/module.js +++ b/lib/module.js @@ -95,8 +95,15 @@ class Module { if (!moduleOpts) { return } + // Allow using babel style array options + if(Array.isArray(moduleOpts)) { + moduleOpts = { + src: moduleOpts[0], + options: moduleOpts[1] + } + } // Allows passing runtime options to each module - const options = moduleOpts.options || {} + const options = moduleOpts.options || (typeof moduleOpts === 'object' ? moduleOpts : {}) const originalSrc = moduleOpts.src || moduleOpts // Resolve module let module = originalSrc From 30b5387f95a863bb1030ed9bc3fd971b9205caec Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 31 May 2017 19:28:36 +0430 Subject: [PATCH 18/24] test(module): code coverage --- lib/module.js | 2 +- test/fixtures/module/nuxt.config.js | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/module.js b/lib/module.js index 2f54eb6ab5..106f04b41c 100755 --- a/lib/module.js +++ b/lib/module.js @@ -96,7 +96,7 @@ class Module { return } // Allow using babel style array options - if(Array.isArray(moduleOpts)) { + if (Array.isArray(moduleOpts)) { moduleOpts = { src: moduleOpts[0], options: moduleOpts[1] diff --git a/test/fixtures/module/nuxt.config.js b/test/fixtures/module/nuxt.config.js index 9272e7ca93..19e591d11d 100755 --- a/test/fixtures/module/nuxt.config.js +++ b/test/fixtures/module/nuxt.config.js @@ -2,8 +2,13 @@ module.exports = { loading: true, modules: [ '~modules/basic', - '~/modules/middleware', - './modules/template' + { + src: '~/modules/middleware', + options: { + foo: 'bar' + } + }, + ['./modules/template', {baz: 'ping'}] ], serverMiddleware: [ './modules/middleware/midd2' From ea03d76e852cad1f614ed810ce8476eca664f574 Mon Sep 17 00:00:00 2001 From: Sebastien Chopin Date: Fri, 2 Jun 2017 12:15:38 +0200 Subject: [PATCH 19/24] Fix issue #829 with onNuxtReady undefined --- lib/app/index.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/app/index.js b/lib/app/index.js index 9e80d20401..a812d16426 100644 --- a/lib/app/index.js +++ b/lib/app/index.js @@ -12,9 +12,19 @@ import App from '<%= appPath %>' import { getContext } from './utils' +if (process.browser) { + // window.onNuxtReady(() => console.log('Ready')) hook + // Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading) + window._nuxtReadyCbs = [] + window.onNuxtReady = function (cb) { + window._nuxtReadyCbs.push(cb) + } +} + // Import SSR plugins <% plugins.forEach(function (plugin) { if (plugin.ssr) -{ %>import <%= plugin.name %> from '<%= r(plugin.src) %>' +{ %>let <%= plugin.name %> = require('<%= r(plugin.src) %>') +<%= plugin.name %> = <%= plugin.name %>.default || <%= plugin.name %> <% }}) %> // Component: @@ -58,12 +68,6 @@ async function createApp (ssrContext) { store.replaceState(window.__NUXT__.state) } <% } %> - // window.onNuxtReady(() => console.log('Ready')) hook - // Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading) - window._nuxtReadyCbs = [] - window.onNuxtReady = function (cb) { - window._nuxtReadyCbs.push(cb) - } } // root instance From 1ae30622830b2c582f58c73df6f57e66bfd93cd8 Mon Sep 17 00:00:00 2001 From: Sebastien Chopin Date: Fri, 2 Jun 2017 17:58:53 +0200 Subject: [PATCH 20/24] Add nuxt.ready(), dev depends on process.env.NODE_ENV, server waits for modules to be ready and build() is called on development by default --- lib/build.js | 19 +++++++++++++++++-- lib/module.js | 10 ++++------ lib/nuxt.js | 19 ++++++++++++++++++- lib/render.js | 8 ++++++++ lib/server.js | 20 +++++++++++++------- test/index.test.js | 6 ++++-- 6 files changed, 64 insertions(+), 18 deletions(-) diff --git a/lib/build.js b/lib/build.js index a5793131a3..a12807e06c 100644 --- a/lib/build.js +++ b/lib/build.js @@ -97,8 +97,21 @@ export function options () { } export async function build () { - // Initialize modules first - await this.module.init() + // Avoid calling this method multiple times + if (this._buildDone) { + return this + } + // If building + if (this._building) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(this.build()) + }, 300) + }) + } + this._building = true + // Wait for Nuxt.js to be ready + await this.ready() // Check if pages dir exists and warn if not this._nuxtPages = typeof this.createRoutes !== 'function' if (this._nuxtPages) { @@ -123,6 +136,8 @@ export async function build () { await generateRoutesAndFiles.call(this) // Generate .nuxt/dist/ files await buildFiles.call(this) + // Flag to set that building is done + this._buildDone = true return this } diff --git a/lib/module.js b/lib/module.js index 106f04b41c..f16669697a 100755 --- a/lib/module.js +++ b/lib/module.js @@ -13,18 +13,16 @@ class Module { this.nuxt = nuxt this.options = nuxt.options this.modules = [] - this.initialized = false + this.initing = this.ready() } - async init () { - if (this.initialized) { - debug('[nuxt] Modules are already initialized') + async ready () { + if (this.initing) { + await this.initing return } // Install all modules in sequence await sequence(this.options.modules, this.addModule.bind(this)) - // Indicate modules are already initialized - this.initialized = true } addVendor (vendor) { diff --git a/lib/nuxt.js b/lib/nuxt.js index c045e483c2..bce21038cc 100644 --- a/lib/nuxt.js +++ b/lib/nuxt.js @@ -16,7 +16,7 @@ import * as utils from './utils' class Nuxt { constructor (options = {}) { const defaults = { - dev: true, + dev: (process.env.NODE_ENV !== 'production'), buildDir: '.nuxt', env: {}, head: { @@ -72,6 +72,8 @@ class Nuxt { } if (typeof options.transition === 'string') options.transition = { name: options.transition } this.options = _.defaultsDeep(options, defaults) + // Ready variable + this._ready = false // Env variables this.dev = this.options.dev // Explicit srcDir, rootDir and buildDir @@ -121,6 +123,21 @@ class Nuxt { this.utils = utils // Add module integration this.module = new Module(this) + // Init nuxt.js + this.ready() + // Launch build in development but don't wait for him to be finished + if (this.dev) { + this.build() + } + // Return nuxt.js instance + return this + } + + async ready () { + if (this._ready) return this + // Init modules + await this.module.ready() + this._ready = true } close (callback) { diff --git a/lib/render.js b/lib/render.js index ccdaefc07f..ee8d371d9c 100644 --- a/lib/render.js +++ b/lib/render.js @@ -23,6 +23,9 @@ export async function render (req, res) { }, 1000) }) } + // Wait for nuxt.js to be ready + await this.ready() + // Get context const context = getContext(req, res) res.statusCode = 200 try { @@ -92,6 +95,7 @@ export async function render (req, res) { return err } const html = this.errorTemplate({ + /* istanbul ignore if */ error: err, stack: ansiHTML(encodeHtml(err.stack)) }) @@ -104,6 +108,9 @@ export async function render (req, res) { } export async function renderRoute (url, context = {}) { + // Wait for modules to be initialized + await this.ready() + // Log rendered url debug(`Rendering url ${url}`) // Add url and isSever to the context context.url = url @@ -165,6 +172,7 @@ export async function renderAndGetWindow (url, opts = {}) { const { window } = await jsdom.JSDOM.fromURL(url, options) // If Nuxt could not be loaded (error from the server-side) const nuxtExists = window.document.body.innerHTML.includes('window.__NUXT__') + /* istanbul ignore if */ if (!nuxtExists) { let error = new Error('Could not load the nuxt app') error.body = window.document.body.innerHTML diff --git a/lib/server.js b/lib/server.js index 5ad4439529..63766e4563 100644 --- a/lib/server.js +++ b/lib/server.js @@ -10,12 +10,15 @@ class Server { // Initialize this.app = connect() this.server = http.createServer(this.app) - // Add Middleware - this.nuxt.options.serverMiddleware.forEach(m => { - this.useMiddleware(m) + this.nuxt.ready() + .then(() => { + // Add Middleware + this.nuxt.options.serverMiddleware.forEach(m => { + this.useMiddleware(m) + }) + // Add default render middleware + this.useMiddleware(this.render.bind(this)) }) - // Add default render middleware - this.useMiddleware(this.render.bind(this)) return this } @@ -45,8 +48,11 @@ class Server { listen (port, host) { host = host || '127.0.0.1' port = port || 3000 - this.server.listen(port, host, () => { - console.log('Ready on http://%s:%s', host, port) // eslint-disable-line no-console + this.nuxt.ready() + .then(() => { + this.server.listen(port, host, () => { + console.log('Ready on http://%s:%s', host, port) // eslint-disable-line no-console + }) }) return this } diff --git a/test/index.test.js b/test/index.test.js index 53f05b9afa..f910f1ea5e 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -7,12 +7,14 @@ test('Nuxt.js Class', t => { t.is(typeof Nuxt, 'function') }) -test('Nuxt.js Instance', async t => { +test.serial('Nuxt.js Instance', async t => { + process.env.NODE_ENV = 'production' const nuxt = new Nuxt() t.is(typeof nuxt, 'object') - t.is(nuxt.dev, true) + t.is(nuxt.dev, false) t.is(typeof nuxt.build, 'function') t.is(typeof nuxt.generate, 'function') + delete process.env.NODE_ENV }) test.serial('Fail when build not done and try to render', async t => { From 2b80bc3e5c2186deaa0e1a2aee1df21432328d3b Mon Sep 17 00:00:00 2001 From: Sebastien Chopin Date: Fri, 2 Jun 2017 17:59:20 +0200 Subject: [PATCH 21/24] No need to call build() on development --- bin/nuxt-dev | 6 ------ 1 file changed, 6 deletions(-) diff --git a/bin/nuxt-dev b/bin/nuxt-dev index 7b2a36bda2..4b1f733ce6 100755 --- a/bin/nuxt-dev +++ b/bin/nuxt-dev @@ -46,12 +46,6 @@ var server = nuxt.server = new nuxt.Server(nuxt).listen(port, host) listenOnConfigChanges(nuxt, server) -nuxt.build() - .catch((err) => { - console.error(err) // eslint-disable-line no-console - process.exit(1) - }) - function listenOnConfigChanges(nuxt, server) { // Listen on nuxt.config.js changes var build = _.debounce(() => { From 5682eef2a509adbb2733eb222934d6f83e001ddb Mon Sep 17 00:00:00 2001 From: Sebastien Chopin Date: Fri, 2 Jun 2017 18:09:20 +0200 Subject: [PATCH 22/24] Update coverage --- lib/render.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/render.js b/lib/render.js index ee8d371d9c..fcfb741613 100644 --- a/lib/render.js +++ b/lib/render.js @@ -172,9 +172,10 @@ export async function renderAndGetWindow (url, opts = {}) { const { window } = await jsdom.JSDOM.fromURL(url, options) // If Nuxt could not be loaded (error from the server-side) const nuxtExists = window.document.body.innerHTML.includes('window.__NUXT__') - /* istanbul ignore if */ if (!nuxtExists) { + /* istanbul ignore next */ let error = new Error('Could not load the nuxt app') + /* istanbul ignore next */ error.body = window.document.body.innerHTML throw error } From f958801fff7734c55ea277752752dc112dc55dc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Sun, 4 Jun 2017 14:08:36 +0200 Subject: [PATCH 23/24] fix: modules called before renderer in production --- lib/build.js | 33 +++++++++++++++++---------------- lib/generate.js | 4 ++++ lib/module.js | 3 ++- lib/nuxt.js | 19 ++++++++++++------- lib/render.js | 5 +++-- 5 files changed, 38 insertions(+), 26 deletions(-) diff --git a/lib/build.js b/lib/build.js index a12807e06c..968feee155 100644 --- a/lib/build.js +++ b/lib/build.js @@ -76,23 +76,24 @@ export function options () { if (this.dev && isUrl(this.options.build.publicPath)) { this.options.build.publicPath = defaults.publicPath } +} + +export function production () { // Production, create server-renderer - if (!this.dev) { - webpackStats = { - chunks: false, - children: false, - modules: false, - colors: true - } - const serverConfig = getWebpackServerConfig.call(this) - const bundlePath = join(serverConfig.output.path, 'server-bundle.json') - const manifestPath = join(serverConfig.output.path, 'client-manifest.json') - if (fs.existsSync(bundlePath) && fs.existsSync(manifestPath)) { - const bundle = fs.readFileSync(bundlePath, 'utf8') - const manifest = fs.readFileSync(manifestPath, 'utf8') - createRenderer.call(this, JSON.parse(bundle), JSON.parse(manifest)) - addAppTemplate.call(this) - } + webpackStats = { + chunks: false, + children: false, + modules: false, + colors: true + } + const serverConfig = getWebpackServerConfig.call(this) + const bundlePath = join(serverConfig.output.path, 'server-bundle.json') + const manifestPath = join(serverConfig.output.path, 'client-manifest.json') + if (fs.existsSync(bundlePath) && fs.existsSync(manifestPath)) { + const bundle = fs.readFileSync(bundlePath, 'utf8') + const manifest = fs.readFileSync(manifestPath, 'utf8') + createRenderer.call(this, JSON.parse(bundle), JSON.parse(manifest)) + addAppTemplate.call(this) } } diff --git a/lib/generate.js b/lib/generate.js index 65de915b46..7525cb843d 100644 --- a/lib/generate.js +++ b/lib/generate.js @@ -42,6 +42,10 @@ export default async function () { const s = Date.now() let errors = [] /* + ** Wait for modules to be initialized + */ + await this.ready() + /* ** Set variables */ this.options.generate = _.defaultsDeep(this.options.generate, defaults) diff --git a/lib/module.js b/lib/module.js index f16669697a..83deb63533 100755 --- a/lib/module.js +++ b/lib/module.js @@ -19,10 +19,11 @@ class Module { async ready () { if (this.initing) { await this.initing - return + return this } // Install all modules in sequence await sequence(this.options.modules, this.addModule.bind(this)) + return this } addVendor (vendor) { diff --git a/lib/nuxt.js b/lib/nuxt.js index bce21038cc..ee28be97cf 100644 --- a/lib/nuxt.js +++ b/lib/nuxt.js @@ -124,20 +124,25 @@ class Nuxt { // Add module integration this.module = new Module(this) // Init nuxt.js - this.ready() - // Launch build in development but don't wait for him to be finished - if (this.dev) { - this.build() - } + this._ready = this.ready() // Return nuxt.js instance return this } async ready () { - if (this._ready) return this + if (this._ready) { + await this._ready + return this + } // Init modules await this.module.ready() - this._ready = true + // Launch build in development but don't wait for it to be finished + if (this.dev) { + this.build() + } else { + build.production.call(this) + } + return this } close (callback) { diff --git a/lib/render.js b/lib/render.js index fcfb741613..0cc56b79df 100644 --- a/lib/render.js +++ b/lib/render.js @@ -11,6 +11,9 @@ debug.color = 4 setAnsiColors(ansiHTML) export async function render (req, res) { + // Wait for nuxt.js to be ready + await this.ready() + // Check if project is built for production if (!this.renderer && !this.dev) { console.error('> No build files found, please run `nuxt build` before launching `nuxt start`') // eslint-disable-line no-console process.exit(1) @@ -23,8 +26,6 @@ export async function render (req, res) { }, 1000) }) } - // Wait for nuxt.js to be ready - await this.ready() // Get context const context = getContext(req, res) res.statusCode = 200 From 2f32d03f83de48fc13718815e38197446d538b5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Sun, 4 Jun 2017 14:11:18 +0200 Subject: [PATCH 24/24] Bump to alpha3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ec97f4e412..f78ff073d6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nuxt", - "version": "1.0.0-alpha2", + "version": "1.0.0-alpha.3", "description": "A minimalistic framework for server-rendered Vue.js applications (inspired by Next.js)", "contributors": [ {