Unverified Commit 86808bbc authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add basePath support (#9872)

* Add basePath support

* Add tests including copy of HMR tests

* Add production tests

* Add tests for serverless target

* Add missing quotes
parent 2d0ad7d4
...@@ -77,6 +77,7 @@ export function createEntrypoints( ...@@ -77,6 +77,7 @@ export function createEntrypoints(
generateEtags: config.generateEtags, generateEtags: config.generateEtags,
ampBindInitData: config.experimental.ampBindInitData, ampBindInitData: config.experimental.ampBindInitData,
canonicalBase: config.canonicalBase, canonicalBase: config.canonicalBase,
basePath: config.experimental.basePath,
} }
Object.keys(pages).forEach(page => { Object.keys(pages).forEach(page => {
......
...@@ -724,6 +724,9 @@ export default async function getBaseWebpackConfig( ...@@ -724,6 +724,9 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_REACT_MODE': JSON.stringify( 'process.env.__NEXT_REACT_MODE': JSON.stringify(
config.experimental.reactMode config.experimental.reactMode
), ),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(
config.experimental.basePath
),
...(isServer ...(isServer
? { ? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`) // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
......
...@@ -21,6 +21,7 @@ export type ServerlessLoaderQuery = { ...@@ -21,6 +21,7 @@ export type ServerlessLoaderQuery = {
ampBindInitData: boolean | string ampBindInitData: boolean | string
generateEtags: string generateEtags: string
canonicalBase: string canonicalBase: string
basePath: string
} }
const nextServerlessLoader: loader.Loader = function() { const nextServerlessLoader: loader.Loader = function() {
...@@ -36,8 +37,10 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -36,8 +37,10 @@ const nextServerlessLoader: loader.Loader = function() {
absoluteDocumentPath, absoluteDocumentPath,
absoluteErrorPath, absoluteErrorPath,
generateEtags, generateEtags,
basePath,
}: ServerlessLoaderQuery = }: ServerlessLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/') const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace( const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
/\\/g, /\\/g,
...@@ -128,6 +131,16 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -128,6 +131,16 @@ const nextServerlessLoader: loader.Loader = function() {
export default async (req, res) => { export default async (req, res) => {
try { try {
await initServer() await initServer()
${
basePath
? `
if(req.url.startsWith('${basePath}')) {
req.url = req.url.replace('${basePath}', '')
}
`
: ''
}
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
const params = ${ const params = ${
...@@ -181,6 +194,15 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -181,6 +194,15 @@ const nextServerlessLoader: loader.Loader = function() {
export const config = ComponentInfo['confi' + 'g'] || {} export const config = ComponentInfo['confi' + 'g'] || {}
export const _app = App export const _app = App
export async function renderReqToHTML(req, res, fromExport, _renderOpts, _params) { export async function renderReqToHTML(req, res, fromExport, _renderOpts, _params) {
${
basePath
? `
if(req.url.startsWith('${basePath}')) {
req.url = req.url.replace('${basePath}', '')
}
`
: ''
}
const options = { const options = {
App, App,
Document, Document,
......
...@@ -18,6 +18,12 @@ import { isDynamicRoute } from './utils/is-dynamic' ...@@ -18,6 +18,12 @@ import { isDynamicRoute } from './utils/is-dynamic'
import { getRouteMatcher } from './utils/route-matcher' import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex' import { getRouteRegex } from './utils/route-regex'
function addBasePath(path: string): string {
// @ts-ignore variable is always a string
const p: string = process.env.__NEXT_ROUTER_BASEPATH
return path.indexOf(p) !== 0 ? p + path : path
}
function toRoute(path: string): string { function toRoute(path: string): string {
return path.replace(/\/$/, '') || '/' return path.replace(/\/$/, '') || '/'
} }
...@@ -284,7 +290,7 @@ export default class Router implements BaseRouter { ...@@ -284,7 +290,7 @@ export default class Router implements BaseRouter {
if (!options._h && this.onlyAHashChange(as)) { if (!options._h && this.onlyAHashChange(as)) {
this.asPath = as this.asPath = as
Router.events.emit('hashChangeStart', as) Router.events.emit('hashChangeStart', as)
this.changeState(method, url, as) this.changeState(method, url, addBasePath(as))
this.scrollToHash(as) this.scrollToHash(as)
Router.events.emit('hashChangeComplete', as) Router.events.emit('hashChangeComplete', as)
return resolve(true) return resolve(true)
...@@ -346,7 +352,7 @@ export default class Router implements BaseRouter { ...@@ -346,7 +352,7 @@ export default class Router implements BaseRouter {
} }
Router.events.emit('beforeHistoryChange', as) Router.events.emit('beforeHistoryChange', as)
this.changeState(method, url, as, options) this.changeState(method, url, addBasePath(as), options)
const hash = window.location.hash.substring(1) const hash = window.location.hash.substring(1)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
......
...@@ -53,6 +53,7 @@ const defaultConfig: { [key: string]: any } = { ...@@ -53,6 +53,7 @@ const defaultConfig: { [key: string]: any } = {
deferScripts: false, deferScripts: false,
reactMode: 'legacy', reactMode: 'legacy',
workerThreads: false, workerThreads: false,
basePath: '',
}, },
future: { future: {
excludeDefaultMomentLocales: false, excludeDefaultMomentLocales: false,
...@@ -106,10 +107,45 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -106,10 +107,45 @@ function assignDefaults(userConfig: { [key: string]: any }) {
`Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://err.sh/zeit/next.js/invalid-assetprefix` `Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://err.sh/zeit/next.js/invalid-assetprefix`
) )
} }
if (result.experimental && result.experimental.css) { if (result.experimental) {
if (result.experimental.css) {
// The new CSS support requires granular chunks be enabled. // The new CSS support requires granular chunks be enabled.
result.experimental.granularChunks = true result.experimental.granularChunks = true
} }
if (typeof result.experimental.basePath !== 'string') {
throw new Error(
`Specified basePath is not a string, found type "${typeof result
.experimental.basePath}"`
)
}
if (result.experimental.basePath !== '') {
if (result.experimental.basePath === '/') {
throw new Error(
`Specified basePath /. basePath has to be either an empty string or a path prefix"`
)
}
if (!result.experimental.basePath.startsWith('/')) {
throw new Error(
`Specified basePath has to start with a /, found "${result.experimental.basePath}"`
)
}
if (result.experimental.basePath !== '/') {
if (result.experimental.basePath.endsWith('/')) {
throw new Error(
`Specified basePath should not end with /, found "${result.experimental.basePath}"`
)
}
if (result.assetPrefix === '') {
result.assetPrefix = result.experimental.basePath
}
}
}
}
return result return result
} }
......
...@@ -232,6 +232,16 @@ export default class Server { ...@@ -232,6 +232,16 @@ export default class Server {
parsedUrl.query = parseQs(parsedUrl.query) parsedUrl.query = parseQs(parsedUrl.query)
} }
if (parsedUrl.pathname!.startsWith(this.nextConfig.experimental.basePath)) {
// If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
parsedUrl.pathname =
parsedUrl.pathname!.replace(
this.nextConfig.experimental.basePath,
''
) || '/'
req.url = req.url!.replace(this.nextConfig.experimental.basePath, '')
}
res.statusCode = 200 res.statusCode = 200
return this.run(req, res, parsedUrl).catch(err => { return this.run(req, res, parsedUrl).catch(err => {
this.logError(err) this.logError(err)
......
export default () => <div>test chunkfilename</div>
import React from 'react'
import PropTypes from 'prop-types'
export default class extends React.Component {
static contextTypes = {
data: PropTypes.object,
}
render() {
const { data } = this.context
return <div>{data.title}</div>
}
}
export default () => <p>Hello World 1</p>
export default () => <p>Hello World 2</p>
export default () => <p>Hello World 1</p>
export default () => <p>Hello World 2</p>
export default () => {
return (
<div id="dynamic-component">
Dynamic Component
<style jsx>{`
div {
font-size: 100px;
}
`}</style>
</div>
)
}
import dynamic from 'next/dynamic'
const Nested2 = dynamic(() => import('./nested2'))
export default () => (
<div>
Nested 1
<Nested2 />
</div>
)
import dynamic from 'next/dynamic'
const BrowserLoaded = dynamic(async () => () => <div>Browser hydrated</div>, {
ssr: false,
})
export default () => (
<div>
<div>Nested 2</div>
<BrowserLoaded />
</div>
)
import React from 'react'
export default class Welcome extends React.Component {
state = { name: null }
componentDidMount() {
const { name } = this.props
this.setState({ name })
}
render() {
const { name } = this.state
if (!name) return null
return <p>Welcome, {name}</p>
}
}
module.exports = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
experimental: {
basePath: '/docs',
},
}
import Link from 'next/link'
export default () => (
<Link href="/other-page">
<a id="other-page-link">
<h1>Hello World</h1>
</a>
</Link>
)
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => {
return (
<div className="hmr-about-page">
<p>This is the about page.</p>
</div>
)
}
export default () => (
<div className="hmr-contact-page">
<p>This is the contact page.</p>
</div>
)
import React from 'react'
export default class Counter extends React.Component {
state = { count: 0 }
incr() {
const { count } = this.state
this.setState({ count: count + 1 })
}
render() {
return (
<div>
<p>COUNT: {this.state.count}</p>
<button onClick={() => this.incr()}>Increment</button>
</div>
)
}
}
import React from 'react'
export default class extends React.Component {
static getInitialProps() {
const error = new Error('an-expected-error-in-gip')
throw error
}
render() {
return <div>Hello</div>
}
}
import Link from 'next/link'
export default () => (
<div>
<Link href="/hmr/error-in-gip">
<a id="error-in-gip-link">Bad Page</a>
</Link>
</div>
)
import React from 'react'
import dynamic from 'next/dynamic'
const HmrDynamic = dynamic(import('../../components/hmr/dynamic'))
export default () => {
return <HmrDynamic />
}
import React, { Component } from 'react'
export default class StyleStateFul extends Component {
render() {
return (
<React.Fragment>
<div className="hmr-style-page">
<p>
This is the style page.
<style jsx>{`
p {
font-size: 100px;
}
`}</style>
</p>
</div>
</React.Fragment>
)
}
}
import React from 'react'
export default () => {
return (
<React.Fragment>
<div className="hmr-style-page">
<p>
This is the style page.
<style jsx>{`
p {
font-size: 100px;
}
`}</style>
</p>
</div>
</React.Fragment>
)
}
export default () => <h1 id="other-page-title">Hello Other</h1>
function SSRPage({ test }) {
return <h1>{test}</h1>
}
SSRPage.getInitialProps = () => {
return {
test: 'hello',
}
}
export default SSRPage
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment