首页 > 解决方案 > 如何使用 next-optimized-images 和 next.js basePath 配置

问题描述

我正在使用next-optimized-images来优化我的 SwiperSlides 中使用的图像。

我的图像数组:

const deviceImages = [
    {
        "size": "lg",
        "type": "front",
        "colourName": "Green",
        "s_code": "S0479969",
        "altText": "front view",
        "url": "/images/devices/apple-iphone-11-green-lg-front.png"
    }, {
        "size": "lg",
        "type": "back",
        "colourName": "Green",
        "s_code": "S0479969",
        "altText": "back view",
        "url": "/images/devices/apple-iphone-11-green-lg-back.png"
    }
];

我的 next.config.js:

const isProd = process.env.NODE_ENV === 'production'
const withPlugins = require('next-compose-plugins');
const optimizedImages = require('next-optimized-images');

module.exports = withPlugins([
    [optimizedImages, {

    }],
    {
        basePath: isProd ? '/products/mobile' : '',
        exportTrailingSlash: true
    }
]);

我的 .env.local:

NEXT_PUBLIC_BASE_PATH=/products/mobile

没有下一个优化图像的我的 SwiperSlides - 按预期工作

{deviceImages.map((image, index) => (
    <SwiperSlide key={index}>
        <img src={`${IS_PRODUCTION ? process.env.NEXT_PUBLIC_BASE_PATH : ''}${image.url}`} alt={image.altText} loading={index === 0 ? 'eager' : 'lazy'}/>
    </SwiperSlide>
))}

我的 SwiperSlide 与下一个优化图像

{deviceImages.map((image, index) => (
    <SwiperSlide key={index + 3}>
        <img src={require(`../../../../../public${image.url}`)} alt={image.altText} loading={index === 0 ? 'eager' : 'lazy'}/>
    </SwiperSlide>
))}

在本地运行良好,但在生产环境中路径不正确。路径是,例如:

www.example.com/_next/static/chunks/images/...

在 prod 环境中,我需要帮助来制定路径:

www.example.com/products/mobile/_next/static/chunks/images/...

标签: reactjstypescriptnext.jsswiper

解决方案


推荐阅读