I am using Next.js v14 to create a page with the configuration in the attached image.
In index.module.scss
, I am using an image for the background.
Below is a portion of the code.
&::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;
}
The image specified in url
is in /public/img
, so the image path in url
starts at /img
.
I want to change the path of url
in index.module.scss
in npm run dev
and npm run build
.
The dev
is localhost:3000
, so I can leave it as it is, but for the build
I want it to be on the second level sampledomain.com/path-to-site/
.
No search, no blog post, and no answer using Chat GPT.
For example, the answer was to put the environment variable in front of the path, but I get an error.
Also, I don’t know how to configure webpack
in next.config.js
, because I have no knowledge of webpack
.
2
Answers
you need to define the asset prefix in your next.config.js file.
in your SCSS file, you can reference the background images
Environment variables will not work if you put them in front of the path because they are primarily designed to run with js file. However, you can still make use of it by importing an empty component with css using environment variable as condition.
First you will need to place the css of two environments into two separated css files (
localBackground.css
andbuildBackground.css
)Then, you will need two empty components that do nothing but import the css file (
BackgroundLocal.tsx
andBackgroundBuild.tsx
). The content of these two files can simply be like below:After this, you will need to dynamically import these two files with condition checking based on environment variables:
Hope this can help!