client.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. import Vue from 'vue'
  2. import middleware from './middleware'
  3. import {
  4. applyAsyncData,
  5. sanitizeComponent,
  6. resolveRouteComponents,
  7. getMatchedComponents,
  8. getMatchedComponentsInstances,
  9. flatMapComponents,
  10. setContext,
  11. middlewareSeries,
  12. promisify,
  13. getLocation,
  14. compile,
  15. getQueryDiff,
  16. globalHandleError
  17. } from './utils'
  18. import { createApp, NuxtError } from './index'
  19. const noopData = () => { return {} }
  20. const noopFetch = () => {}
  21. // Global shared references
  22. let _lastPaths = []
  23. let app
  24. let router
  25. // Try to rehydrate SSR data from window
  26. const NUXT = window.__NUXT__ || {}
  27. Object.assign(Vue.config, {"silent":false,"performance":true})
  28. // Setup global Vue error handler
  29. if (!Vue.config.$nuxt) {
  30. const defaultErrorHandler = Vue.config.errorHandler
  31. Vue.config.errorHandler = (err, vm, info, ...rest) => {
  32. // Call other handler if exist
  33. let handled = null
  34. if (typeof defaultErrorHandler === 'function') {
  35. handled = defaultErrorHandler(err, vm, info, ...rest)
  36. }
  37. if (handled === true) {
  38. return handled
  39. }
  40. if (vm && vm.$root) {
  41. const nuxtApp = Object.keys(Vue.config.$nuxt)
  42. .find(nuxtInstance => vm.$root[nuxtInstance])
  43. // Show Nuxt Error Page
  44. if (nuxtApp && vm.$root[nuxtApp].error && info !== 'render function') {
  45. vm.$root[nuxtApp].error(err)
  46. }
  47. }
  48. if (typeof defaultErrorHandler === 'function') {
  49. return handled
  50. }
  51. // Log to console
  52. if (process.env.NODE_ENV !== 'production') {
  53. console.error(err)
  54. } else {
  55. console.error(err.message || err)
  56. }
  57. }
  58. Vue.config.$nuxt = {}
  59. }
  60. Vue.config.$nuxt.$nuxt = true
  61. // Create and mount App
  62. createApp()
  63. .then(mountApp)
  64. .catch((err) => {
  65. console.error('[nuxt] Error while initializing app', err)
  66. })
  67. function componentOption(component, key, ...args) {
  68. if (!component || !component.options || !component.options[key]) {
  69. return {}
  70. }
  71. const option = component.options[key]
  72. if (typeof option === 'function') {
  73. return option(...args)
  74. }
  75. return option
  76. }
  77. function mapTransitions(Components, to, from) {
  78. const componentTransitions = (component) => {
  79. const transition = componentOption(component, 'transition', to, from) || {}
  80. return (typeof transition === 'string' ? { name: transition } : transition)
  81. }
  82. return Components.map((Component) => {
  83. // Clone original object to prevent overrides
  84. const transitions = Object.assign({}, componentTransitions(Component))
  85. // Combine transitions & prefer `leave` transitions of 'from' route
  86. if (from && from.matched.length && from.matched[0].components.default) {
  87. const fromTransitions = componentTransitions(from.matched[0].components.default)
  88. Object.keys(fromTransitions)
  89. .filter(key => fromTransitions[key] && key.toLowerCase().includes('leave'))
  90. .forEach((key) => { transitions[key] = fromTransitions[key] })
  91. }
  92. return transitions
  93. })
  94. }
  95. async function loadAsyncComponents(to, from, next) {
  96. // Check if route path changed (this._pathChanged), only if the page is not an error (for validate())
  97. this._pathChanged = !!app.nuxt.err || from.path !== to.path
  98. this._queryChanged = JSON.stringify(to.query) !== JSON.stringify(from.query)
  99. this._diffQuery = (this._queryChanged ? getQueryDiff(to.query, from.query) : [])
  100. if (this._pathChanged && this.$loading.start && !this.$loading.manual) {
  101. this.$loading.start()
  102. }
  103. try {
  104. const Components = await resolveRouteComponents(to)
  105. if (!this._pathChanged && this._queryChanged) {
  106. // Add a marker on each component that it needs to refresh or not
  107. const startLoader = Components.some((Component) => {
  108. const watchQuery = Component.options.watchQuery
  109. if (watchQuery === true) return true
  110. if (Array.isArray(watchQuery)) {
  111. return watchQuery.some(key => this._diffQuery[key])
  112. }
  113. return false
  114. })
  115. if (startLoader && this.$loading.start && !this.$loading.manual) {
  116. this.$loading.start()
  117. }
  118. }
  119. // Call next()
  120. next()
  121. } catch (err) {
  122. this.error(err)
  123. this.$nuxt.$emit('routeChanged', to, from, error)
  124. next(false)
  125. }
  126. }
  127. function applySSRData(Component, ssrData) {
  128. if (NUXT.serverRendered && ssrData) {
  129. applyAsyncData(Component, ssrData)
  130. }
  131. Component._Ctor = Component
  132. return Component
  133. }
  134. // Get matched components
  135. function resolveComponents(router) {
  136. const path = getLocation(router.options.base, router.options.mode)
  137. return flatMapComponents(router.match(path), async (Component, _, match, key, index) => {
  138. // If component is not resolved yet, resolve it
  139. if (typeof Component === 'function' && !Component.options) {
  140. Component = await Component()
  141. }
  142. // Sanitize it and save it
  143. const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null)
  144. match.components[key] = _Component
  145. return _Component
  146. })
  147. }
  148. function callMiddleware(Components, context, layout) {
  149. let midd = []
  150. let unknownMiddleware = false
  151. // If layout is undefined, only call global middleware
  152. if (typeof layout !== 'undefined') {
  153. midd = [] // Exclude global middleware if layout defined (already called before)
  154. if (layout.middleware) {
  155. midd = midd.concat(layout.middleware)
  156. }
  157. Components.forEach((Component) => {
  158. if (Component.options.middleware) {
  159. midd = midd.concat(Component.options.middleware)
  160. }
  161. })
  162. }
  163. midd = midd.map((name) => {
  164. if (typeof name === 'function') return name
  165. if (typeof middleware[name] !== 'function') {
  166. unknownMiddleware = true
  167. this.error({ statusCode: 500, message: 'Unknown middleware ' + name })
  168. }
  169. return middleware[name]
  170. })
  171. if (unknownMiddleware) return
  172. return middlewareSeries(midd, context)
  173. }
  174. async function render(to, from, next) {
  175. if (this._pathChanged === false && this._queryChanged === false) return next()
  176. // Handle first render on SPA mode
  177. if (to === from) _lastPaths = []
  178. else {
  179. const fromMatches = []
  180. _lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => {
  181. return compile(from.matched[fromMatches[i]].path)(from.params)
  182. })
  183. }
  184. // nextCalled is true when redirected
  185. let nextCalled = false
  186. const _next = (path) => {
  187. if (from.path === path.path && this.$loading.finish) {
  188. this.$loading.finish()
  189. }
  190. if (from.path !== path.path && this.$loading.pause) {
  191. this.$loading.pause()
  192. }
  193. if (nextCalled) return
  194. nextCalled = true
  195. next(path)
  196. }
  197. // Update context
  198. await setContext(app, {
  199. route: to,
  200. from,
  201. next: _next.bind(this)
  202. })
  203. this._dateLastError = app.nuxt.dateErr
  204. this._hadError = !!app.nuxt.err
  205. // Get route's matched components
  206. const matches = []
  207. const Components = getMatchedComponents(to, matches)
  208. // If no Components matched, generate 404
  209. if (!Components.length) {
  210. // Default layout
  211. await callMiddleware.call(this, Components, app.context)
  212. if (nextCalled) return
  213. // Load layout for error page
  214. const layout = await this.loadLayout(
  215. typeof NuxtError.layout === 'function'
  216. ? NuxtError.layout(app.context)
  217. : NuxtError.layout
  218. )
  219. await callMiddleware.call(this, Components, app.context, layout)
  220. if (nextCalled) return
  221. // Show error page
  222. app.context.error({ statusCode: 404, message: `This page could not be found` })
  223. return next()
  224. }
  225. // Update ._data and other properties if hot reloaded
  226. Components.forEach((Component) => {
  227. if (Component._Ctor && Component._Ctor.options) {
  228. Component.options.asyncData = Component._Ctor.options.asyncData
  229. Component.options.fetch = Component._Ctor.options.fetch
  230. }
  231. })
  232. // Apply transitions
  233. this.setTransitions(mapTransitions(Components, to, from))
  234. try {
  235. // Call middleware
  236. await callMiddleware.call(this, Components, app.context)
  237. if (nextCalled) return
  238. if (app.context._errored) return next()
  239. // Set layout
  240. let layout = Components[0].options.layout
  241. if (typeof layout === 'function') {
  242. layout = layout(app.context)
  243. }
  244. layout = await this.loadLayout(layout)
  245. // Call middleware for layout
  246. await callMiddleware.call(this, Components, app.context, layout)
  247. if (nextCalled) return
  248. if (app.context._errored) return next()
  249. // Call .validate()
  250. let isValid = true
  251. try {
  252. for (const Component of Components) {
  253. if (typeof Component.options.validate !== 'function') {
  254. continue
  255. }
  256. isValid = await Component.options.validate(app.context)
  257. if (!isValid) {
  258. break
  259. }
  260. }
  261. } catch (validationError) {
  262. // ...If .validate() threw an error
  263. this.error({
  264. statusCode: validationError.statusCode || '500',
  265. message: validationError.message
  266. })
  267. return next()
  268. }
  269. // ...If .validate() returned false
  270. if (!isValid) {
  271. this.error({ statusCode: 404, message: `This page could not be found` })
  272. return next()
  273. }
  274. // Call asyncData & fetch hooks on components matched by the route.
  275. await Promise.all(Components.map((Component, i) => {
  276. // Check if only children route changed
  277. Component._path = compile(to.matched[matches[i]].path)(to.params)
  278. Component._dataRefresh = false
  279. // Check if Component need to be refreshed (call asyncData & fetch)
  280. // Only if its slug has changed or is watch query changes
  281. if ((this._pathChanged && this._queryChanged) || Component._path !== _lastPaths[i]) {
  282. Component._dataRefresh = true
  283. } else if (!this._pathChanged && this._queryChanged) {
  284. const watchQuery = Component.options.watchQuery
  285. if (watchQuery === true) {
  286. Component._dataRefresh = true
  287. } else if (Array.isArray(watchQuery)) {
  288. Component._dataRefresh = watchQuery.some(key => this._diffQuery[key])
  289. }
  290. }
  291. if (!this._hadError && this._isMounted && !Component._dataRefresh) {
  292. return Promise.resolve()
  293. }
  294. const promises = []
  295. const hasAsyncData = (
  296. Component.options.asyncData &&
  297. typeof Component.options.asyncData === 'function'
  298. )
  299. const hasFetch = !!Component.options.fetch
  300. const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45
  301. // Call asyncData(context)
  302. if (hasAsyncData) {
  303. const promise = promisify(Component.options.asyncData, app.context)
  304. .then((asyncDataResult) => {
  305. applyAsyncData(Component, asyncDataResult)
  306. if (this.$loading.increase) {
  307. this.$loading.increase(loadingIncrease)
  308. }
  309. })
  310. promises.push(promise)
  311. }
  312. // Check disabled page loading
  313. this.$loading.manual = Component.options.loading === false
  314. // Call fetch(context)
  315. if (hasFetch) {
  316. let p = Component.options.fetch(app.context)
  317. if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) {
  318. p = Promise.resolve(p)
  319. }
  320. p.then((fetchResult) => {
  321. if (this.$loading.increase) {
  322. this.$loading.increase(loadingIncrease)
  323. }
  324. })
  325. promises.push(p)
  326. }
  327. return Promise.all(promises)
  328. }))
  329. // If not redirected
  330. if (!nextCalled) {
  331. if (this.$loading.finish && !this.$loading.manual) {
  332. this.$loading.finish()
  333. }
  334. next()
  335. }
  336. } catch (err) {
  337. const error = err || {}
  338. if (error.message === 'ERR_REDIRECT') {
  339. return this.$nuxt.$emit('routeChanged', to, from, error)
  340. }
  341. _lastPaths = []
  342. globalHandleError(error)
  343. // Load error layout
  344. let layout = NuxtError.layout
  345. if (typeof layout === 'function') {
  346. layout = layout(app.context)
  347. }
  348. await this.loadLayout(layout)
  349. this.error(error)
  350. this.$nuxt.$emit('routeChanged', to, from, error)
  351. next(false)
  352. }
  353. }
  354. // Fix components format in matched, it's due to code-splitting of vue-router
  355. function normalizeComponents(to, ___) {
  356. flatMapComponents(to, (Component, _, match, key) => {
  357. if (typeof Component === 'object' && !Component.options) {
  358. // Updated via vue-router resolveAsyncComponents()
  359. Component = Vue.extend(Component)
  360. Component._Ctor = Component
  361. match.components[key] = Component
  362. }
  363. return Component
  364. })
  365. }
  366. function showNextPage(to) {
  367. // Hide error component if no error
  368. if (this._hadError && this._dateLastError === this.$options.nuxt.dateErr) {
  369. this.error()
  370. }
  371. // Set layout
  372. let layout = this.$options.nuxt.err
  373. ? NuxtError.layout
  374. : to.matched[0].components.default.options.layout
  375. if (typeof layout === 'function') {
  376. layout = layout(app.context)
  377. }
  378. this.setLayout(layout)
  379. }
  380. // When navigating on a different route but the same component is used, Vue.js
  381. // Will not update the instance data, so we have to update $data ourselves
  382. function fixPrepatch(to, ___) {
  383. if (this._pathChanged === false && this._queryChanged === false) return
  384. Vue.nextTick(() => {
  385. const matches = []
  386. const instances = getMatchedComponentsInstances(to, matches)
  387. const Components = getMatchedComponents(to, matches)
  388. instances.forEach((instance, i) => {
  389. if (!instance) return
  390. // if (
  391. // !this._queryChanged &&
  392. // to.matched[matches[i]].path.indexOf(':') === -1 &&
  393. // to.matched[matches[i]].path.indexOf('*') === -1
  394. // ) return // If not a dynamic route, skip
  395. if (
  396. instance.constructor._dataRefresh &&
  397. Components[i] === instance.constructor &&
  398. typeof instance.constructor.options.data === 'function'
  399. ) {
  400. const newData = instance.constructor.options.data.call(instance)
  401. for (const key in newData) {
  402. Vue.set(instance.$data, key, newData[key])
  403. }
  404. }
  405. })
  406. showNextPage.call(this, to)
  407. // Hot reloading
  408. setTimeout(() => hotReloadAPI(this), 100)
  409. })
  410. }
  411. function nuxtReady(_app) {
  412. window.onNuxtReadyCbs.forEach((cb) => {
  413. if (typeof cb === 'function') {
  414. cb(_app)
  415. }
  416. })
  417. // Special JSDOM
  418. if (typeof window._onNuxtLoaded === 'function') {
  419. window._onNuxtLoaded(_app)
  420. }
  421. // Add router hooks
  422. router.afterEach((to, from) => {
  423. // Wait for fixPrepatch + $data updates
  424. Vue.nextTick(() => _app.$nuxt.$emit('routeChanged', to, from))
  425. })
  426. }
  427. // Special hot reload with asyncData(context)
  428. function getNuxtChildComponents($parent, $components = []) {
  429. $parent.$children.forEach(($child) => {
  430. if ($child.$vnode.data.nuxtChild && !$components.find(c =>(c.$options.__file === $child.$options.__file))) {
  431. $components.push($child)
  432. }
  433. if ($child.$children && $child.$children.length) {
  434. getNuxtChildComponents($child, $components)
  435. }
  436. })
  437. return $components
  438. }
  439. function hotReloadAPI(_app) {
  440. if (!module.hot) return
  441. let $components = getNuxtChildComponents(_app.$nuxt, [])
  442. $components.forEach(addHotReload.bind(_app))
  443. }
  444. function addHotReload($component, depth) {
  445. if ($component.$vnode.data._hasHotReload) return
  446. $component.$vnode.data._hasHotReload = true
  447. var _forceUpdate = $component.$forceUpdate.bind($component.$parent)
  448. $component.$vnode.context.$forceUpdate = async () => {
  449. let Components = getMatchedComponents(router.currentRoute)
  450. let Component = Components[depth]
  451. if (!Component) return _forceUpdate()
  452. if (typeof Component === 'object' && !Component.options) {
  453. // Updated via vue-router resolveAsyncComponents()
  454. Component = Vue.extend(Component)
  455. Component._Ctor = Component
  456. }
  457. this.error()
  458. let promises = []
  459. const next = function (path) {
  460. this.$loading.finish && this.$loading.finish()
  461. router.push(path)
  462. }
  463. await setContext(app, {
  464. route: router.currentRoute,
  465. isHMR: true,
  466. next: next.bind(this)
  467. })
  468. const context = app.context
  469. if (this.$loading.start && !this.$loading.manual) this.$loading.start()
  470. callMiddleware.call(this, Components, context)
  471. .then(() => {
  472. // If layout changed
  473. if (depth !== 0) return Promise.resolve()
  474. let layout = Component.options.layout || 'default'
  475. if (typeof layout === 'function') {
  476. layout = layout(context)
  477. }
  478. if (this.layoutName === layout) return Promise.resolve()
  479. let promise = this.loadLayout(layout)
  480. promise.then(() => {
  481. this.setLayout(layout)
  482. Vue.nextTick(() => hotReloadAPI(this))
  483. })
  484. return promise
  485. })
  486. .then(() => {
  487. return callMiddleware.call(this, Components, context, this.layout)
  488. })
  489. .then(() => {
  490. // Call asyncData(context)
  491. let pAsyncData = promisify(Component.options.asyncData || noopData, context)
  492. pAsyncData.then((asyncDataResult) => {
  493. applyAsyncData(Component, asyncDataResult)
  494. this.$loading.increase && this.$loading.increase(30)
  495. })
  496. promises.push(pAsyncData)
  497. // Call fetch()
  498. Component.options.fetch = Component.options.fetch || noopFetch
  499. let pFetch = Component.options.fetch(context)
  500. if (!pFetch || (!(pFetch instanceof Promise) && (typeof pFetch.then !== 'function'))) { pFetch = Promise.resolve(pFetch) }
  501. pFetch.then(() => this.$loading.increase && this.$loading.increase(30))
  502. promises.push(pFetch)
  503. return Promise.all(promises)
  504. })
  505. .then(() => {
  506. this.$loading.finish && this.$loading.finish()
  507. _forceUpdate()
  508. setTimeout(() => hotReloadAPI(this), 100)
  509. })
  510. }
  511. }
  512. async function mountApp(__app) {
  513. // Set global variables
  514. app = __app.app
  515. router = __app.router
  516. // Resolve route components
  517. const Components = await Promise.all(resolveComponents(router))
  518. // Create Vue instance
  519. const _app = new Vue(app)
  520. // Mounts Vue app to DOM element
  521. const mount = () => {
  522. _app.$mount('#__nuxt')
  523. // Listen for first Vue update
  524. Vue.nextTick(() => {
  525. // Call window.{{globals.readyCallback}} callbacks
  526. nuxtReady(_app)
  527. // Enable hot reloading
  528. hotReloadAPI(_app)
  529. })
  530. }
  531. // Enable transitions
  532. _app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app)
  533. if (Components.length) {
  534. _app.setTransitions(mapTransitions(Components, router.currentRoute))
  535. _lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params))
  536. }
  537. // Initialize error handler
  538. _app.$loading = {} // To avoid error while _app.$nuxt does not exist
  539. if (NUXT.error) _app.error(NUXT.error)
  540. // Add router hooks
  541. router.beforeEach(loadAsyncComponents.bind(_app))
  542. router.beforeEach(render.bind(_app))
  543. router.afterEach(normalizeComponents)
  544. router.afterEach(fixPrepatch.bind(_app))
  545. // If page already is server rendered
  546. if (NUXT.serverRendered) {
  547. mount()
  548. return
  549. }
  550. // First render on client-side
  551. render.call(_app, router.currentRoute, router.currentRoute, (path) => {
  552. // If not redirected
  553. if (!path) {
  554. normalizeComponents(router.currentRoute, router.currentRoute)
  555. showNextPage.call(_app, router.currentRoute)
  556. // Don't call fixPrepatch.call(_app, router.currentRoute, router.currentRoute) since it's first render
  557. mount()
  558. return
  559. }
  560. // Push the path and then mount app
  561. router.push(path, () => mount(), (err) => {
  562. if (!err) return mount()
  563. console.error(err)
  564. })
  565. })
  566. }