开发和构建时如何更改Next.js v14 css模块中背景图像的路径

问题描述 投票:0回答:1

我正在使用 Next.js v14 创建一个具有附图中配置的页面。

index.module.scss
中,我使用图像作为背景。

下面是部分代码。

    &::before {
        left: 0;
        background: url(/img/pc/index_hero_bg1.png) 0 0 repeat-x;
    }

    &::after {
        right: 0;
        background: url(/img/pc/index_hero_bg2.png) 0 0 repeat-x;
    }

url
中指定的图像位于
/public/img
中,因此
url
中的图像路径从
/img
开始。

我想更改

url
index.module.scss
npm run dev
npm run build
的路径。

dev
localhost:3000
,所以我可以保持原样,但对于
build
我希望它位于第二层
sampledomain.com/path-to-site/

没有搜索,没有博客文章,使用聊天 GPT 也没有答案。

例如,答案是将环境变量放在路径前面,但我收到错误。

另外,我不知道如何在

webpack
中配置
next.config.js
,因为我对
webpack
一无所知。

javascript next.js next.js13 css-modules next.js14
1个回答
0
投票

您需要在 next.config.js 文件中定义资产前缀。

// next.config.js
module.exports = {
  basePath: '/path-to-site', // This sets the base path for your application
  assetPrefix: '/path-to-site/', // This sets the asset prefix for your assets
};

在您的SCSS文件中,您可以引用背景图片

&::before {
    left: 0;
    background: url('/img/pc/index_hero_bg1.png') 0 0 repeat-x;
}

&::after {
    right: 0;
    background: url('/img/pc/index_hero_bg2.png') 0 0 repeat-x;
}
© www.soinside.com 2019 - 2024. All rights reserved.