为next/image配置主机名



我正试图从next/image升级我的NextJS与<Image />。我的图像是远程托管的。似乎要使远程图像工作,我需要将我的域添加到next.config.js

我的做法如下:

const withTM = require('next-transpile-modules')([
'@maxmind/geoip2-node',
'amp-html',
'lodash-es',
]); // pass the modules you would like to see transpiled
const withImages = require('next-images');
const webpack = require('webpack');
const { uniq } = require('lodash');
const makeWithbundleAnalyzer = require('@next/bundle-analyzer');
const withPlugins = require('next-compose-plugins');
const withSourceMaps = require('@zeit/next-source-maps');
const { assetBaseUrl } = require('./lib/AssetHelper');
const { env: environmentVariables } = require('./app.json');
// Set env vars before running webpack
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line global-require
require('dotenv-flow').config();
}
module.exports = {
analyticsId: analyticsId,
};
const withBundleAnalyzer = makeWithbundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
});
// For all env vars required by the app:
// - throw an error if required but not set in env
// - serialize  non-sensitive env vars where sensitive flag is set
function serializeEnvVariables() {
return Object.entries(environmentVariables).reduce(
(hash, [key, { serialize }]) => {
const value = process.env[key];
if (serialize) {
return { ...hash, [key]: JSON.stringify(value) };
}
return hash;
},
{}
);
}
const securityHeaders = [
{
key: 'referrer-policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'x-content-type-options',
value: 'nosniff',
},
{
key: 'x-download-options',
value: 'noopen',
},
{
key: 'x-frame-options',
value: 'SAMEORIGIN',
},
{
key: 'x-permitted-cross-domain-policies',
value: 'none',
},
{
key: 'x-xss-protection',
value: '1; mode=block',
},
];
module.exports = withPlugins(
[withBundleAnalyzer, withImages, withSourceMaps, withTM],
{
// Append the domain where the assets are hosted
assetPrefix: assetBaseUrl(),
images: {
domains: ['static.mydomain.com'],
disableStaticImages: true,
},
i18n: {
locales: ['en', 'es'],
defaultLocale: 'en',
},
async headers() {
return [
{
source: '/:path*',
headers: securityHeaders,
},
];
},
async redirects() {
return [
{
source: '/consumer-guides/:path*',
destination: '/guides/:path*',
permanent: true,
},
];
},
// Customize webpack config for next.js
// _config is the default next.js webpack configuration
webpack(_config, { isServer }) {
// Reassign to allow changes and appease linter
const config = _config;
const oldEntry = config.entry;
let remoteConfigFile;
// currently, firebase-admin will blow up if so much as imported on the
// client
if (process.env.INTEGRATION_TESTING) {
remoteConfigFile = './integrationTestRemoteConfig';
} else if (isServer) {
remoteConfigFile = './serverSideRemoteConfig';
} else {
remoteConfigFile = './standardRemoteConfig';
}
config.resolve.alias = {
// Sentry requires different packages for front and back end,
// so use an alias that will automatically choose the correct
// version
'sentry-alias': isServer ? '@sentry/node' : '@sentry/browser',
'@/remoteConfig': remoteConfigFile,
...config.resolve.alias,
};
config.externals.push('fs', 'net');
// Fill in process.env on the client
config.plugins.push(
new webpack.DefinePlugin({
'process.serializedEnv': serializeEnvVariables(),
})
);
// It seems like there should be some way to get the next
// static folder, but I can't find anywhere it's configured
// by next, seems to just be hardcoded.
config.output.publicPath = `${this.assetPrefix}/_next/`;
// Add new rules to previous rules
config.module.rules.push(
// Allow us to import markdown files
{
test: /.md$/,
loader: 'raw-loader',
},
{
resolve: { mainFields: ['module', 'main'] },
},
// temporary fix for when process is undefined with react-markdown: https://github.com/vfile/vfile/issues/38#issuecomment-683198538
// perm fix, see: https://www.pivotaltracker.com/story/show/178868237
{
test: /node_modules/vfile/core.js/,
use: [
{
loader: 'imports-loader',
options: {
type: 'commonjs',
imports: ['single process/browser process'],
},
},
],
}
);
config.entry = async function entry() {
const entries = await oldEntry();
// Add our customer initializers before any other code
if (entries['main.js']) {
// NOTE: these are only included in the client bundle, if you want
// something added on the server you must import it in server.js
entries['main.js'].unshift('./configs/initialize/index.js');
entries['main.js'] = uniq(entries['main.js']);
}
return entries;
};
return config;
},
}
);

然而,它不适合我。我得到一个错误:

Error: Invalid src prop (https://static.mydomain.com/images/forsale/2020/03/19/01/16/my_item_for_sale.jpeg) on `next/image`, hostname "static.mydomain.com" is not configured under images in your `next.config.js`

我做错了什么?为什么domains: ['static.mydomain.com']不允许我使用以'static.mydomain.com'开头的url ?

我有两个建议可以解决你的问题。添加尝试导入的所有文件格式:

images: {
domains: ['static.mydomain.com'],
formats: ['image/jpeg'],
},

或者删除disableStaticImages: true,因为它不允许您导入静态文件作为src属性。

最新更新