Unverified Commit 3b55a37c authored by Perry Olsson's avatar Perry Olsson Committed by GitHub

Webpack rule to block importing images into _document (#28475)

parent c4f9f1e1
# Images cannot be imported into your custom document.
#### Why This Error Occurred
An attempt to import an image file into [`pages/_document.js`](https://nextjs.org/docs/advanced-features/custom-document) was made.
Custom documents aren't compiled for the browser and images statically imported like this will not be displayed.
#### Possible Ways to Fix It
If your image needs to be displayed on every page you can relocate it to your [`pages/_app.js`](https://nextjs.org/docs/advanced-features/custom-app) file.
#### Example
```jsx
//pages/_app.js
import yourImage from "path/to/your/image"
import Image from "next/image"
function MyApp({ Component, pageProps }) {
return (
<>
<Image src={yourImage} alt="your_image_description" />
<Component {...pageProps} />
</>
}
export default MyApp
```
### Useful Links
- [Custom `Document`](https://nextjs.org/docs/advanced-features/custom-document)
- [Custom `App`](https://nextjs.org/docs/advanced-features/custom-app)
- [Static File Serving](https://nextjs.org/docs/basic-features/static-file-serving)
......@@ -4,6 +4,10 @@
"title": "Messages",
"heading": true,
"routes": [
{
"title": "custom-document-image-import",
"path": "/errors/custom-document-image-import.md"
},
{
"title": "404-get-initial-props",
"path": "/errors/404-get-initial-props.md"
......
import curry from 'next/dist/compiled/lodash.curry'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { loader } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
import { getCustomDocumentImageError } from './messages'
export const images = curry(async function images(
_ctx: ConfigurationContext,
config: webpack.Configuration
) {
const fns: ConfigurationFn[] = [
loader({
oneOf: [
{
test: /\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i,
use: {
loader: 'error-loader',
options: {
reason: getCustomDocumentImageError(),
},
},
issuer: /pages[\\/]_document\./,
},
],
}),
]
const fn = pipe(...fns)
return fn(config)
})
import chalk from 'chalk'
export function getCustomDocumentImageError() {
return `Images ${chalk.bold('cannot')} be imported within ${chalk.cyan(
'pages/_document.js'
)}. Please move image imports that need to be displayed on every page into ${chalk.cyan(
'pages/_app.js'
)}.\nRead more: https://nextjs.org/docs/messages/custom-document-image-import`
}
......@@ -2,6 +2,7 @@ import { webpack } from 'next/dist/compiled/webpack/webpack'
import { NextConfigComplete } from '../../../server/config-shared'
import { base } from './blocks/base'
import { css } from './blocks/css'
import { images } from './blocks/images'
import { ConfigurationContext, pipe } from './utils'
export async function build(
......@@ -46,6 +47,6 @@ export async function build(
isCraCompat,
}
const fn = pipe(base(ctx), css(ctx))
const fn = pipe(base(ctx), css(ctx), images(ctx))
return fn(config)
}
import Document, { Html, Head, Main, NextScript } from 'next/document'
import Image from 'next/image'
import img from '../public/test.jpg'
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Image src={img} />
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
export default function home() {
return <div>hello</div>
}
/* eslint-env jest */
import { nextBuild } from 'next-test-utils'
import { join } from 'path'
jest.setTimeout(1000 * 60 * 2)
describe('Invalid static image import in _document', () => {
it('Should fail to build', async () => {
const appDir = join(__dirname, '..')
const { code, stderr } = await nextBuild(appDir, [], {
stderr: true,
})
expect(code).not.toBe(0)
expect(stderr).toContain('Failed to compile')
expect(stderr).toMatch(
/Images.*cannot.*be imported within.*pages[\\/]_document\.js/
)
expect(stderr).toMatch(/Location:.*pages[\\/]_document\.js/)
})
})
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