Commit a6ddaefe authored by JJ Kasper's avatar JJ Kasper Committed by Tim Neutkens

Add experimental exportTrailingSlash config (#6664)

By default when `next export`ing a Next.js application we will automatically append a `/` to all urls to be fully compatible with the directory structure being output.

However since most platforms support directory indexes it makes sense to change this default in the future.

This PR adds `exportTrailingSlash` as experimental flag. We'll try this out for a bit on nextjs.org / zeit.co/docs before introducing it as new option.

The default value is `true` as this is the current behavior in stable Next.js.

```
{
  experimental: {
    exportTrailingSlash: false
  }
}
```

⚠️ as with all experimental flags being added this is subject to breaking between canary/stable versions.
parent fbedce4d
...@@ -205,10 +205,12 @@ export default class Router implements IRouterInterface { ...@@ -205,10 +205,12 @@ export default class Router implements IRouterInterface {
// Add the ending slash to the paths. So, we can serve the // Add the ending slash to the paths. So, we can serve the
// "<page>/index.html" directly for the SSR page. // "<page>/index.html" directly for the SSR page.
if (process.env.__NEXT_EXPORT_TRAILING_SLASH) {
// @ts-ignore this is temporarily global (attached to window) // @ts-ignore this is temporarily global (attached to window)
if (__NEXT_DATA__.nextExport) { if (__NEXT_DATA__.nextExport) {
as = Router._rewriteUrlForNextExport(as) as = Router._rewriteUrlForNextExport(as)
} }
}
this.abortComponentLoad(as) this.abortComponentLoad(as)
......
...@@ -28,7 +28,8 @@ const defaultConfig = { ...@@ -28,7 +28,8 @@ const defaultConfig = {
(Number(process.env.CIRCLE_NODE_TOTAL) || (Number(process.env.CIRCLE_NODE_TOTAL) ||
(os.cpus() || { length: 1 }).length) - 1 (os.cpus() || { length: 1 }).length) - 1
), ),
profiling: false profiling: false,
exportTrailingSlash: true
} }
} }
......
...@@ -244,6 +244,7 @@ export default function getBaseWebpackConfig (dir: string, {dev = false, isServe ...@@ -244,6 +244,7 @@ export default function getBaseWebpackConfig (dir: string, {dev = false, isServe
...(dev && !isServer ? { ...(dev && !isServer ? {
'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir) 'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir)
} : {}), } : {}),
'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(config.experimental.exportTrailingSlash)
}), }),
!isServer && new ReactLoadablePlugin({ !isServer && new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST filename: REACT_LOADABLE_MANIFEST
......
...@@ -14,7 +14,7 @@ function isLocal (href) { ...@@ -14,7 +14,7 @@ function isLocal (href) {
(url.protocol === origin.protocol && url.host === origin.host) (url.protocol === origin.protocol && url.host === origin.host)
} }
function memoizedFormatUrl (formatUrl) { function memoizedFormatUrl (formatFunc) {
let lastHref = null let lastHref = null
let lastAs = null let lastAs = null
let lastResult = null let lastResult = null
...@@ -23,7 +23,7 @@ function memoizedFormatUrl (formatUrl) { ...@@ -23,7 +23,7 @@ function memoizedFormatUrl (formatUrl) {
return lastResult return lastResult
} }
const result = formatUrl(href, as) const result = formatFunc(href, as)
lastHref = href lastHref = href
lastAs = as lastAs = as
lastResult = result lastResult = result
...@@ -31,6 +31,12 @@ function memoizedFormatUrl (formatUrl) { ...@@ -31,6 +31,12 @@ function memoizedFormatUrl (formatUrl) {
} }
} }
function formatUrl (url) {
return url && typeof url === 'object'
? formatWithValidation(url)
: url
}
class Link extends Component { class Link extends Component {
componentDidMount () { componentDidMount () {
this.prefetch() this.prefetch()
...@@ -46,12 +52,8 @@ class Link extends Component { ...@@ -46,12 +52,8 @@ class Link extends Component {
// as per https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html // as per https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
formatUrls = memoizedFormatUrl((href, asHref) => { formatUrls = memoizedFormatUrl((href, asHref) => {
return { return {
href: href && typeof href === 'object' href: formatUrl(href),
? formatWithValidation(href) as: formatUrl(asHref, true)
: href,
as: asHref && typeof asHref === 'object'
? formatWithValidation(asHref)
: asHref
} }
}) })
...@@ -136,6 +138,7 @@ class Link extends Component { ...@@ -136,6 +138,7 @@ class Link extends Component {
// Add the ending slash to the paths. So, we can serve the // Add the ending slash to the paths. So, we can serve the
// "<page>/index.html" directly. // "<page>/index.html" directly.
if (process.env.__NEXT_EXPORT_TRAILING_SLASH) {
if ( if (
props.href && props.href &&
typeof __NEXT_DATA__ !== 'undefined' && typeof __NEXT_DATA__ !== 'undefined' &&
...@@ -143,6 +146,7 @@ class Link extends Component { ...@@ -143,6 +146,7 @@ class Link extends Component {
) { ) {
props.href = _Router._rewriteUrlForNextExport(props.href) props.href = _Router._rewriteUrlForNextExport(props.href)
} }
}
return React.cloneElement(child, props) return React.cloneElement(child, props)
} }
......
...@@ -9,6 +9,9 @@ module.exports = (phase) => { ...@@ -9,6 +9,9 @@ module.exports = (phase) => {
serverRuntimeConfig: { serverRuntimeConfig: {
bar: 'bar' bar: 'bar'
}, },
experimental: {
// exportTrailingSlash: false
},
exportPathMap: function () { exportPathMap: function () {
return { return {
'/': { page: '/' }, '/': { page: '/' },
......
...@@ -13,6 +13,24 @@ export default function (context) { ...@@ -13,6 +13,24 @@ export default function (context) {
browser.close() browser.close()
}) })
it('should add trailing slash on Link', async () => {
const browser = await webdriver(context.port, '/')
const link = await browser
.elementByCss('#about-via-link')
.getAttribute('href')
expect(link.substr(link.length - 1)).toBe('/')
})
it('should not add trailing slash on Link when disabled', async () => {
const browser = await webdriver(context.portNoTrailSlash, '/')
const link = await browser
.elementByCss('#about-via-link')
.getAttribute('href')
expect(link.substr(link.length - 1)).not.toBe('/')
})
it('should do navigations via Link', async () => { it('should do navigations via Link', async () => {
const browser = await webdriver(context.port, '/') const browser = await webdriver(context.port, '/')
const text = await browser const text = await browser
......
...@@ -64,12 +64,21 @@ describe('Static Export', () => { ...@@ -64,12 +64,21 @@ describe('Static Export', () => {
}) })
beforeAll(async () => { beforeAll(async () => {
const outdir = join(appDir, 'out') const outdir = join(appDir, 'out')
const outNoTrailSlash = join(appDir, 'outNoTrailSlash')
await nextBuild(appDir) await nextBuild(appDir)
await nextExport(appDir, { outdir }) await nextExport(appDir, { outdir })
nextConfig.replace(`// exportTrailingSlash: false`, `exportTrailingSlash: false`)
await nextBuild(appDir)
await nextExport(appDir, { outdir: outNoTrailSlash })
context.server = await startStaticServer(join(appDir, 'out')) context.server = await startStaticServer(join(appDir, 'out'))
context.port = context.server.address().port context.port = context.server.address().port
context.serverNoTrailSlash = await startStaticServer(outNoTrailSlash)
context.portNoTrailSlash = context.serverNoTrailSlash.address().port
devContext.port = await findPort() devContext.port = await findPort()
devContext.server = await launchApp(join(__dirname, '../'), devContext.port, true) devContext.server = await launchApp(join(__dirname, '../'), devContext.port, true)
...@@ -82,7 +91,8 @@ describe('Static Export', () => { ...@@ -82,7 +91,8 @@ describe('Static Export', () => {
afterAll(async () => { afterAll(async () => {
await Promise.all([ await Promise.all([
stopApp(context.server), stopApp(context.server),
killApp(devContext.server) killApp(devContext.server),
stopApp(context.serverNoTrailSlash)
]) ])
nextConfig.restore() nextConfig.restore()
}) })
......
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