mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
e093441bad
* Speed up next build
* Document webpack config
* Speed up next build
* Remove comment
* Add comment
* Clean up rules
* Add comments
* Run in parallel
* Push plugins seperately
* Create a new chunk for react
* Don’t uglify react since it’s already uglified. Move react to commons in development
* Use the minified version directly
* Re-add globpattern
* Move loaders into a separate variable
* Add comment linking to Dan’s explanation
* Remove dot
* Add universal webpack
* Initial dev support
* Fix linting
* Add changes from Arunoda's work
* Made next dev works.
But super slow and no HMR support.
* Fix client side hot reload
* Server side hmr
* Only in dev
* Add on-demand-entries client + hot-middleware
* Add .babelrc support
* Speed up on demand entries by running in parallel
* Serve static generated files
* Add missing config in dev
* Add sass support
* Add support for .map
* Add cssloader config and fix .jsx support
* Rename
* use same defaults as css-loader. Fix linting
* Add NoEmitErrorsPlugin
* Add clientBootstrap
* Use webpackhotmiddleware on the multi compiler
* alpha.3
* Use babel 16.2.x
* Fix reloading after error
* Remove comment
* Release 5.0.0-univeral-alpha.1
* Remove check for React 16
* Release 5.0.0-universal-alpha.2
* React hot loader v4
* Use our static file rendering machanism to serve pages.
This should work well since the file path for a page is predictable.
* Release 5.0.0-universal-alpha.3
* Remove optional loaders
* Release 5.0.0-universal-alpha.4
* Remove clientBootstrap
* Remove renderScript
* Make sure pages bundles are served correctly
* Remove unused import
* Revert to using the same code as canary
* Fix hot loader
* Release 5.0.0-universal-alpha.5
* Check if externals dir exist before applying config
* Add typescript support
* Add support for transpiling certain packages in node_modules
Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319
* Add BABEL_DISABLE_CACHE support
* Make sourcemaps in production opt-in
* Revert "Add support for transpiling certain packages in node_modules"
This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da.
In favor of a better api around this.
* Support typescript through next.config.js
* Remove comments
* Bring back commons.js calculation
* Remove unused dependencies
* Move base.config.js to webpack.js
* Make sure to only invalidate webpackDevMiddleware one after other.
* Allow babel-loder caching by default.
* Add comment about preact support
* Bring back buildir replace
* Remove obsolete plugin
* Remove build replace, speed up build
* Resolve page entries like pages/day/index.js to pages/day.js
* Add componentDidCatch back
* Compile to bundles
* Use config.distDir everywhere
* Make sure the file is an array
* Remove console.log
* Apply optimization to uglifyjs
* Add comment pointing to source
* Create entries the same way in dev and production
* Remove unused and broken pagesGlobPattern
* day/index.js is automatically turned into day.js at build time
* Remove poweredByHeader option
* Load pages with the correct path.
* Release 5.0.0-universal-alpha.6
* Make sure react-dom/server can be overwritten by module-alias
* Only add react-hot-loader babel plugin in dev
* Release 5.0.0-universal-alpha.7
* Revert tests
* Release 5.0.0-universal-alpha.10
* Make sure next/head is working properly.
* Add wepack alias for 'next' back.
* Make sure overriding className in next/head works
* Alias react too
* Add missing r
* Fragment fallback has to wrap the children
* Use min.js
* Remove css.js
* Remove wallaby.js
* Release 5.0.0-universal-alpha.11
* Resolve relative to workdir instead of next
* Make sure we touch the right file
* Resolve next modules
* Remove dotjsx removal plugins since we use webpack on the server
* Revert "Resolve relative to workdir instead of next"
This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed.
* Externalize any locally loaded module lives outside of app dir.
* Remove server aliases
* Check node_modules reliably
* Add symlink to next for tests
* Make sure dynamic imports work locally.
This is why we need it: b545b519b2/lib/MainTemplate.js (L68)
We need to have the finally clause in the above in __webpack_require__.
webpack output option strictModuleExceptionHandling does that.
* dynmaic -> dynamic
* Remove webpack-node-externals
* Make sure dynamic imports support SSR.
* Remove css support in favor of next-css
* Make sure we load path from `/` since it’s included in the path matching
* Catch when ensurepage couldn’t be fulfilled for `.js.map`
* Register require cache flusher for both client and server
* Add comment explaining this is to facilitate hot reloading
* Only load module when needed
* Remove unused modules
* Release 5.0.0-universal-alpha.12
* Only log the `found babel` message once
* Make sure ondemand entries working correctly.
Now we are just using a single instance of OnDemandEntryHandler.
* Better sourcemaps
* Release 5.0.0-universal-alpha.13
* Lock uglify version to 1.1.6
* Release 5.0.0-universal-alpha.14
* Fix a typo.
* Introduce multi-zones support for mircofrontends
* Add section on css
373 lines
10 KiB
JavaScript
373 lines
10 KiB
JavaScript
/* global __NEXT_DATA__ */
|
|
|
|
import { parse, format } from 'url'
|
|
import EventEmitter from '../EventEmitter'
|
|
import shallowEquals from '../shallow-equals'
|
|
import PQueue from '../p-queue'
|
|
import { loadGetInitialProps, getURL } from '../utils'
|
|
import { _notifyBuildIdMismatch, _rewriteUrlForNextExport } from './'
|
|
|
|
export default class Router {
|
|
constructor (pathname, query, as, { pageLoader, Component, ErrorComponent, err } = {}) {
|
|
// represents the current component key
|
|
this.route = toRoute(pathname)
|
|
|
|
// set up the component cache (by route keys)
|
|
this.components = {}
|
|
// We should not keep the cache, if there's an error
|
|
// Otherwise, this cause issues when when going back and
|
|
// come again to the errored page.
|
|
if (Component !== ErrorComponent) {
|
|
this.components[this.route] = { Component, err }
|
|
}
|
|
|
|
// Handling Router Events
|
|
this.events = new EventEmitter()
|
|
|
|
this.pageLoader = pageLoader
|
|
this.prefetchQueue = new PQueue({ concurrency: 2 })
|
|
this.ErrorComponent = ErrorComponent
|
|
this.pathname = pathname
|
|
this.query = query
|
|
this.asPath = as
|
|
this.subscriptions = new Set()
|
|
this.componentLoadCancel = null
|
|
this.onPopState = this.onPopState.bind(this)
|
|
|
|
if (typeof window !== 'undefined') {
|
|
// in order for `e.state` to work on the `onpopstate` event
|
|
// we have to register the initial route upon initialization
|
|
this.changeState('replaceState', format({ pathname, query }), getURL())
|
|
|
|
window.addEventListener('popstate', this.onPopState)
|
|
}
|
|
}
|
|
|
|
async onPopState (e) {
|
|
if (!e.state) {
|
|
// We get state as undefined for two reasons.
|
|
// 1. With older safari (< 8) and older chrome (< 34)
|
|
// 2. When the URL changed with #
|
|
//
|
|
// In the both cases, we don't need to proceed and change the route.
|
|
// (as it's already changed)
|
|
// But we can simply replace the state with the new changes.
|
|
// Actually, for (1) we don't need to nothing. But it's hard to detect that event.
|
|
// So, doing the following for (1) does no harm.
|
|
const { pathname, query } = this
|
|
this.changeState('replaceState', format({ pathname, query }), getURL())
|
|
return
|
|
}
|
|
|
|
const { url, as, options } = e.state
|
|
this.replace(url, as, options)
|
|
}
|
|
|
|
update (route, Component) {
|
|
const data = this.components[route]
|
|
if (!data) {
|
|
throw new Error(`Cannot update unavailable route: ${route}`)
|
|
}
|
|
|
|
const newData = { ...data, Component }
|
|
this.components[route] = newData
|
|
|
|
if (route === this.route) {
|
|
this.notify(newData)
|
|
}
|
|
}
|
|
|
|
async reload (route) {
|
|
delete this.components[route]
|
|
this.pageLoader.clearCache(route)
|
|
|
|
if (route !== this.route) return
|
|
|
|
const { pathname, query } = this
|
|
const url = window.location.href
|
|
|
|
this.events.emit('routeChangeStart', url)
|
|
const routeInfo = await this.getRouteInfo(route, pathname, query, url)
|
|
const { error } = routeInfo
|
|
|
|
if (error && error.cancelled) {
|
|
return
|
|
}
|
|
|
|
this.notify(routeInfo)
|
|
|
|
if (error) {
|
|
this.events.emit('routeChangeError', error, url)
|
|
throw error
|
|
}
|
|
|
|
this.events.emit('routeChangeComplete', url)
|
|
}
|
|
|
|
back () {
|
|
window.history.back()
|
|
}
|
|
|
|
push (url, as = url, options = {}) {
|
|
return this.change('pushState', url, as, options)
|
|
}
|
|
|
|
replace (url, as = url, options = {}) {
|
|
return this.change('replaceState', url, as, options)
|
|
}
|
|
|
|
async change (method, _url, _as, options) {
|
|
// If url and as provided as an object representation,
|
|
// we'll format them into the string version here.
|
|
const url = typeof _url === 'object' ? format(_url) : _url
|
|
let as = typeof _as === 'object' ? format(_as) : _as
|
|
|
|
// Add the ending slash to the paths. So, we can serve the
|
|
// "<page>/index.html" directly for the SSR page.
|
|
if (__NEXT_DATA__.nextExport) {
|
|
as = _rewriteUrlForNextExport(as)
|
|
}
|
|
|
|
this.abortComponentLoad(as)
|
|
|
|
// If the url change is only related to a hash change
|
|
// We should not proceed. We should only change the state.
|
|
if (this.onlyAHashChange(as)) {
|
|
this.changeState(method, url, as)
|
|
this.scrollToHash(as)
|
|
return
|
|
}
|
|
|
|
const { pathname, query } = parse(url, true)
|
|
|
|
// If asked to change the current URL we should reload the current page
|
|
// (not location.reload() but reload getInitalProps and other Next.js stuffs)
|
|
// We also need to set the method = replaceState always
|
|
// as this should not go into the history (That's how browsers work)
|
|
if (!this.urlIsNew(pathname, query)) {
|
|
method = 'replaceState'
|
|
}
|
|
|
|
const route = toRoute(pathname)
|
|
const { shallow = false } = options
|
|
let routeInfo = null
|
|
|
|
this.events.emit('routeChangeStart', as)
|
|
|
|
// If shallow === false and other conditions met, we reuse the
|
|
// existing routeInfo for this route.
|
|
// Because of this, getInitialProps would not run.
|
|
if (shallow && this.isShallowRoutingPossible(route)) {
|
|
routeInfo = this.components[route]
|
|
} else {
|
|
routeInfo = await this.getRouteInfo(route, pathname, query, as)
|
|
}
|
|
|
|
const { error } = routeInfo
|
|
|
|
if (error && error.cancelled) {
|
|
return false
|
|
}
|
|
|
|
this.events.emit('beforeHistoryChange', as)
|
|
this.changeState(method, url, as, options)
|
|
const hash = window.location.hash.substring(1)
|
|
|
|
this.set(route, pathname, query, as, { ...routeInfo, hash })
|
|
|
|
if (error) {
|
|
this.events.emit('routeChangeError', error, as)
|
|
throw error
|
|
}
|
|
|
|
this.events.emit('routeChangeComplete', as)
|
|
return true
|
|
}
|
|
|
|
changeState (method, url, as, options = {}) {
|
|
if (method !== 'pushState' || getURL() !== as) {
|
|
window.history[method]({ url, as, options }, null, as)
|
|
}
|
|
}
|
|
|
|
async getRouteInfo (route, pathname, query, as) {
|
|
let routeInfo = null
|
|
|
|
try {
|
|
routeInfo = this.components[route]
|
|
if (!routeInfo) {
|
|
routeInfo = { Component: await this.fetchComponent(route, as) }
|
|
}
|
|
|
|
const { Component } = routeInfo
|
|
|
|
if (typeof Component !== 'function') {
|
|
throw new Error(`The default export is not a React Component in page: "${pathname}"`)
|
|
}
|
|
|
|
const ctx = { pathname, query, asPath: as }
|
|
routeInfo.props = await this.getInitialProps(Component, ctx)
|
|
|
|
this.components[route] = routeInfo
|
|
} catch (err) {
|
|
if (err.buildIdMismatched) {
|
|
// Now we need to reload the page or do the action asked by the user
|
|
_notifyBuildIdMismatch(as)
|
|
// We also need to cancel this current route change.
|
|
// We do it like this.
|
|
err.cancelled = true
|
|
return { error: err }
|
|
}
|
|
|
|
if (err.statusCode === 404) {
|
|
// If there's 404 error for the page, it could be due to two reasons.
|
|
// 1. Page is not exists
|
|
// 2. Page is exists in a different zone
|
|
// We are not sure whether this is actual 404 or exists in a different zone.
|
|
// So, doing a hard reload is the proper way to deal with this.
|
|
window.location.href = as
|
|
|
|
// Changing the URL doesn't block executing the current code path.
|
|
// So, we need to mark it as a cancelled error and stop the routing logic.
|
|
err.cancelled = true
|
|
return { error: err }
|
|
}
|
|
|
|
if (err.cancelled) {
|
|
return { error: err }
|
|
}
|
|
|
|
const Component = this.ErrorComponent
|
|
routeInfo = { Component, err }
|
|
const ctx = { err, pathname, query }
|
|
routeInfo.props = await this.getInitialProps(Component, ctx)
|
|
|
|
routeInfo.error = err
|
|
}
|
|
|
|
return routeInfo
|
|
}
|
|
|
|
set (route, pathname, query, as, data) {
|
|
this.route = route
|
|
this.pathname = pathname
|
|
this.query = query
|
|
this.asPath = as
|
|
this.notify(data)
|
|
}
|
|
|
|
onlyAHashChange (as) {
|
|
if (!this.asPath) return false
|
|
const [ oldUrlNoHash, oldHash ] = this.asPath.split('#')
|
|
const [ newUrlNoHash, newHash ] = as.split('#')
|
|
|
|
// If the urls are change, there's more than a hash change
|
|
if (oldUrlNoHash !== newUrlNoHash) {
|
|
return false
|
|
}
|
|
|
|
// If the hash has changed, then it's a hash only change.
|
|
// This check is necessary to handle both the enter and
|
|
// leave hash === '' cases. The identity case falls through
|
|
// and is treated as a next reload.
|
|
return oldHash !== newHash
|
|
}
|
|
|
|
scrollToHash (as) {
|
|
const [ , hash ] = as.split('#')
|
|
const el = document.getElementById(hash)
|
|
if (el) {
|
|
el.scrollIntoView()
|
|
}
|
|
}
|
|
|
|
urlIsNew (pathname, query) {
|
|
return this.pathname !== pathname || !shallowEquals(query, this.query)
|
|
}
|
|
|
|
isShallowRoutingPossible (route) {
|
|
return (
|
|
// If there's cached routeInfo for the route.
|
|
Boolean(this.components[route]) &&
|
|
// If the route is already rendered on the screen.
|
|
this.route === route
|
|
)
|
|
}
|
|
|
|
async prefetch (url) {
|
|
// We don't add support for prefetch in the development mode.
|
|
// If we do that, our on-demand-entries optimization won't performs better
|
|
if (process.env.NODE_ENV === 'development') return
|
|
|
|
const { pathname } = parse(url)
|
|
const route = toRoute(pathname)
|
|
return this.prefetchQueue.add(() => this.fetchRoute(route))
|
|
}
|
|
|
|
async fetchComponent (route, as) {
|
|
let cancelled = false
|
|
const cancel = this.componentLoadCancel = function () {
|
|
cancelled = true
|
|
}
|
|
|
|
const Component = await this.fetchRoute(route)
|
|
|
|
if (cancelled) {
|
|
const error = new Error(`Abort fetching component for route: "${route}"`)
|
|
error.cancelled = true
|
|
throw error
|
|
}
|
|
|
|
if (cancel === this.componentLoadCancel) {
|
|
this.componentLoadCancel = null
|
|
}
|
|
|
|
return Component
|
|
}
|
|
|
|
async getInitialProps (Component, ctx) {
|
|
let cancelled = false
|
|
const cancel = () => { cancelled = true }
|
|
this.componentLoadCancel = cancel
|
|
|
|
const props = await loadGetInitialProps(Component, ctx)
|
|
|
|
if (cancel === this.componentLoadCancel) {
|
|
this.componentLoadCancel = null
|
|
}
|
|
|
|
if (cancelled) {
|
|
const err = new Error('Loading initial props cancelled')
|
|
err.cancelled = true
|
|
throw err
|
|
}
|
|
|
|
return props
|
|
}
|
|
|
|
async fetchRoute (route) {
|
|
return await this.pageLoader.loadPage(route)
|
|
}
|
|
|
|
abortComponentLoad (as) {
|
|
if (this.componentLoadCancel) {
|
|
this.events.emit('routeChangeError', new Error('Route Cancelled'), as)
|
|
this.componentLoadCancel()
|
|
this.componentLoadCancel = null
|
|
}
|
|
}
|
|
|
|
notify (data) {
|
|
this.subscriptions.forEach((fn) => fn(data))
|
|
}
|
|
|
|
subscribe (fn) {
|
|
this.subscriptions.add(fn)
|
|
return () => this.subscriptions.delete(fn)
|
|
}
|
|
}
|
|
|
|
function toRoute (path) {
|
|
return path.replace(/\/$/, '') || '/'
|
|
}
|