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

De-experimentalize the `public/` folder (#8661)

* Remove experimental.publicDirectory config

* Error when public is set as an output dir

* Remove experimental.publicDirectory checks

* Update publicFiles checking in next build
parent 1a02dfd8
# Can't Override Next Props
#### Why This Error Occurred
Either you set `distDir` to `public` in your `next.config.js` or during `next export` you tried to export to the `public` directory.
This is not allowed due to `public` being a special folder in Next.js used to serve static assets.
#### Possible Ways to Fix It
Use a different `distDir` or export to a different folder.
### Useful Links
- [Static file serving docs](https://nextjs.org/docs#static-file-serving-eg-images)
...@@ -95,6 +95,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -95,6 +95,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
const publicDir = path.join(dir, 'public') const publicDir = path.join(dir, 'public')
const pagesDir = findPagesDir(dir) const pagesDir = findPagesDir(dir)
let publicFiles: string[] = [] let publicFiles: string[] = []
let hasPublicDir = false
let backgroundWork: (Promise<any> | undefined)[] = [] let backgroundWork: (Promise<any> | undefined)[] = []
backgroundWork.push( backgroundWork.push(
...@@ -104,7 +105,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -104,7 +105,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
await verifyTypeScriptSetup(dir, pagesDir) await verifyTypeScriptSetup(dir, pagesDir)
if (config.experimental.publicDirectory) { try {
await fsStat(publicDir)
hasPublicDir = true
} catch (_) {}
if (hasPublicDir) {
publicFiles = await recursiveReadDir(publicDir, /.*/) publicFiles = await recursiveReadDir(publicDir, /.*/)
} }
...@@ -131,10 +137,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -131,10 +137,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
const entrypoints = createEntrypoints(mappedPages, target, buildId, config) const entrypoints = createEntrypoints(mappedPages, target, buildId, config)
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
try { if (hasPublicDir) {
await fsStat(path.join(publicDir, '_next')) try {
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT) await fsStat(path.join(publicDir, '_next'))
} catch (err) {} throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
} catch (err) {}
}
for (let file of publicFiles) { for (let file of publicFiles) {
file = file file = file
......
...@@ -153,6 +153,13 @@ export default async function( ...@@ -153,6 +153,13 @@ export default async function(
// Initialize the output directory // Initialize the output directory
const outDir = options.outdir const outDir = options.outdir
if (outDir === join(dir, 'public')) {
throw new Error(
`The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://err.sh/zeit/next.js/can-not-output-to-public`
)
}
await recursiveDelete(join(outDir)) await recursiveDelete(join(outDir))
await mkdirp(join(outDir, '_next', buildId)) await mkdirp(join(outDir, '_next', buildId))
...@@ -243,12 +250,7 @@ export default async function( ...@@ -243,12 +250,7 @@ export default async function(
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH) const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
// Copy public directory // Copy public directory
if ( if (!options.buildExport && existsSync(publicDir)) {
!options.buildExport &&
nextConfig.experimental &&
nextConfig.experimental.publicDirectory &&
existsSync(publicDir)
) {
log(' copying "public" directory') log(' copying "public" directory')
await recursiveCopy(publicDir, outDir, { await recursiveCopy(publicDir, outDir, {
filter(path) { filter(path) {
......
...@@ -77,6 +77,12 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -77,6 +77,12 @@ function assignDefaults(userConfig: { [key: string]: any }) {
experimentalWarning() experimentalWarning()
} }
if (key === 'distDir' && userConfig[key] === 'public') {
throw new Error(
`The 'public' directory is reserved in Next.js and can not be set as the 'distDir'. https://err.sh/zeit/next.js/can-not-output-to-public`
)
}
const maybeObject = userConfig[key] const maybeObject = userConfig[key]
if (!!maybeObject && maybeObject.constructor === Object) { if (!!maybeObject && maybeObject.constructor === Object) {
userConfig[key] = { userConfig[key] = {
......
...@@ -294,10 +294,7 @@ export default class Server { ...@@ -294,10 +294,7 @@ export default class Server {
}, },
] ]
if ( if (fs.existsSync(this.publicDir)) {
this.nextConfig.experimental.publicDirectory &&
fs.existsSync(this.publicDir)
) {
routes.push(...this.generatePublicRoutes()) routes.push(...this.generatePublicRoutes())
} }
......
...@@ -229,24 +229,21 @@ export default class DevServer extends Server { ...@@ -229,24 +229,21 @@ export default class DevServer extends Server {
// check for a public file, throwing error if there's a // check for a public file, throwing error if there's a
// conflicting page // conflicting page
if (this.nextConfig.experimental.publicDirectory) { if (await this.hasPublicFile(pathname!)) {
if (await this.hasPublicFile(pathname!)) { const pageFile = await findPageFile(
const pageFile = await findPageFile( this.pagesDir!,
this.pagesDir!, normalizePagePath(pathname!),
this.nextConfig.pageExtensions
)
normalizePagePath(pathname!), if (pageFile) {
this.nextConfig.pageExtensions const err = new Error(
`A conflicting public file and page file was found for path ${pathname} https://err.sh/zeit/next.js/conflicting-public-file-page`
) )
res.statusCode = 500
if (pageFile) { return this.renderError(err, req, res, pathname!, {})
const err = new Error(
`A conflicting public file and page file was found for path ${pathname} https://err.sh/zeit/next.js/conflicting-public-file-page`
)
res.statusCode = 500
return this.renderError(err, req, res, pathname!, {})
}
return this.servePublic(req, res, pathname!)
} }
return this.servePublic(req, res, pathname!)
} }
const { finished } = (await this.hotReloader!.run(req, res, parsedUrl)) || { const { finished } = (await this.hotReloader!.run(req, res, parsedUrl)) || {
......
...@@ -4,9 +4,6 @@ module.exports = { ...@@ -4,9 +4,6 @@ module.exports = {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60 maxInactiveAge: 1000 * 60 * 60
}, },
experimental: {
publicDirectory: true
},
webpack (config) { webpack (config) {
config.module.rules.push({ config.module.rules.push({
test: /pages[\\/]hmr[\\/]about/, test: /pages[\\/]hmr[\\/]about/,
......
...@@ -39,7 +39,7 @@ describe('Promise in next config', () => { ...@@ -39,7 +39,7 @@ describe('Promise in next config', () => {
module.exports = { module.exports = {
target: 'server', target: 'server',
experimental: { experimental: {
publicDirectory: true something: true
} }
} }
`) `)
...@@ -52,7 +52,7 @@ describe('Promise in next config', () => { ...@@ -52,7 +52,7 @@ describe('Promise in next config', () => {
module.exports = (phase) => ({ module.exports = (phase) => ({
target: 'server', target: 'server',
experimental: { experimental: {
publicDirectory: true something: true
} }
}) })
`) `)
......
/* eslint-env jest */
/* global jasmine */
import path from 'path'
import fs from 'fs-extra'
import { nextBuild, nextExport } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
const appDir = path.join(__dirname, '..')
const nextConfig = path.join(appDir, 'next.config.js')
describe('Errors on output to public', () => {
it('Throws error when `distDir` is set to public', async () => {
await fs.writeFile(nextConfig, `module.exports = { distDir: 'public' }`)
const results = await nextBuild(appDir, [], { stdout: true, stderr: true })
expect(results.stdout + results.stderr).toMatch(
/The 'public' directory is reserved in Next.js and can not be set as/
)
await fs.remove(nextConfig)
})
it('Throws error when export out dir is public', async () => {
await fs.remove(nextConfig)
await nextBuild(appDir)
const outdir = path.join(appDir, 'public')
const results = await nextExport(
appDir,
{ outdir },
{
stdout: true,
stderr: true
}
)
expect(results.stdout + results.stderr).toMatch(
/The 'public' directory is reserved in Next.js and can not be used as/
)
})
})
...@@ -9,9 +9,6 @@ module.exports = phase => { ...@@ -9,9 +9,6 @@ module.exports = phase => {
serverRuntimeConfig: { serverRuntimeConfig: {
bar: 'bar' bar: 'bar'
}, },
experimental: {
publicDirectory: true
},
exportTrailingSlash: true, exportTrailingSlash: true,
exportPathMap: function () { exportPathMap: function () {
return { return {
......
...@@ -2,8 +2,5 @@ module.exports = { ...@@ -2,8 +2,5 @@ module.exports = {
onDemandEntries: { onDemandEntries: {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60 maxInactiveAge: 1000 * 60 * 60
},
experimental: {
publicDirectory: true
} }
} }
...@@ -4,9 +4,6 @@ module.exports = { ...@@ -4,9 +4,6 @@ module.exports = {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60 maxInactiveAge: 1000 * 60 * 60
}, },
experimental: {
publicDirectory: true
},
// make sure error isn't thrown from empty publicRuntimeConfig // make sure error isn't thrown from empty publicRuntimeConfig
publicRuntimeConfig: {} publicRuntimeConfig: {}
} }
...@@ -4,9 +4,6 @@ module.exports = { ...@@ -4,9 +4,6 @@ module.exports = {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60 maxInactiveAge: 1000 * 60 * 60
}, },
experimental: {
publicDirectory: true
},
// make sure error isn't thrown from empty publicRuntimeConfig // make sure error isn't thrown from empty publicRuntimeConfig
publicRuntimeConfig: {} publicRuntimeConfig: {}
} }
...@@ -180,8 +180,8 @@ export function nextBuild (dir, args = [], opts = {}) { ...@@ -180,8 +180,8 @@ export function nextBuild (dir, args = [], opts = {}) {
return runNextCommand(['build', dir, ...args], opts) return runNextCommand(['build', dir, ...args], opts)
} }
export function nextExport (dir, { outdir }) { export function nextExport (dir, { outdir }, opts = {}) {
return runNextCommand(['export', dir, '--outdir', outdir]) return runNextCommand(['export', dir, '--outdir', outdir], opts)
} }
export function nextStart (dir, port, opts = {}) { export function nextStart (dir, port, opts = {}) {
......
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