Tips for customizing the background-image path in CSS modules for Next.js v14 during development and production

I am currently utilizing Next.js version 14 to construct a webpage with the setup showcased in the image provided below.

https://i.sstatic.net/IMxlm.png

Within my index.module.scss file, I have integrated an image for the background design.

The snippet of code is visible below:

    &::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 the url attribute is located within the /public/img directory, thus the path in the url begins at /img.

I aim to modify the path of the url in the index.module.scss file during both npm run dev and npm run build operations.

During development (dev), which runs locally on localhost:3000, no changes are necessary. However, during production deployment (build), I wish for it to be situated at the second level domain sampledomain.com/path-to-site/.

Please refrain from providing solutions involving web search, blog posts, or responses generated by Chat GPT.

For instance, previous suggestions involved incorporating environment variables before the path, but this resulted in errors.

In addition, I lack knowledge on how to configure webpack within next.config.js, as my expertise does not extend to webpack configurations.

Answer №1

When placing environment variables in front of the path, they may not function as intended because they are primarily meant to work with JavaScript files. However, you can still utilize them by incorporating an empty component with CSS using the environment variable as a condition.

To do this, start by segregating the CSS for two environments into separate files, namely localBackground.css and buildBackground.css.

Next, create two empty components that solely import the corresponding CSS file, named BackgroundLocal.tsx and BackgroundBuild.tsx. The structure of these files is straightforward:

/*for local environment */
import "./localBackground.css";   // link to your CSS file
export default function BackgroundLocal() {
  return <></>;
}

/*for build environment*/
import "./buildBackground.css";   // link to your CSS file
export default function BackgroundBuild() {
  return <></>;
}

Subsequently, dynamically import these two files based on a condition linked to the environment variables:

"use client"
import dynamic from "next/dynamic";
...
const DynamicBgL = dynamic(() => import("@/components/BackgroundLocal"), {
  ssr: false,
});
const DynamicBgB = dynamic(() => import("@/components/BackgroundBuild"), {
  ssr: false,
});

/*IsLocal is an environment variable set to `true` for local development and `false` for production builds*/
const DynamicBG = process.env.IsLocal ? DynamicBgL : DynamicBgB;
...
export default function MainPage(){
  return(
        ...
    <DynamicBG/>
    ...
}

I trust that you find this guidance helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...

Vitejs is currently loading the entire bundle size instead of just the specific selected files

While working with Vue 3 and Vite, I came across an issue that seems quite strange. The Oh Vue Icons library is loading a massive 108 MB of bundle size, which significantly slows down the loading time even in ViteJS. Here's how my setup looks like: im ...

What is the best way to save geolocation coordinates in a Javascript array?

I am attempting to utilize HTML5 geolocation to determine a user's location and then store the latitude and longitude coordinates in an array for future use with Google Maps and SQL statements. However, when I attempt to add these coordinates to the a ...

CSS - owl carousel automatically stretches images to full width

Here is the code snippet that I am working with: $(document).ready(function() { $('.owl-carousel').owlCarousel({ loop:true, items:4, autoplay:true, autoplayTimeout:2000, autoplayHoverPause:true }); }); #owl-demo ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

Issues with Vuex store causing incorrect value retrieval

In troubleshooting this issue, I am encountering a problem. My request to the back end is to retrieve data for display on the front end. The data fetched from the backend consists of recipes stored in an array. Utilizing v-for, I iterate through the array ...

The click functionality is not functioning properly within the .each() loop

For my event handler, I am trying to use click() but it doesn't seem to be working. Here is the code snippet: $('.ajax-close').click(function( event ){ event.preventDefault(); alert('hi'); $( ' ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

After a period of time since the server has been initialized, the function req.isAuthenticated() no

In my Node.js routes.js file, I have a function implemented to check if a request is isAuthenticated before serving it: function isLoggedIn(req, res, next) { if (req.isAuthenticated()) { console.log('Session Expiry '+req.session.cook ...

How can I submit multiple dropdown menus when they are changed?

I recently added Four dropdown menus on my index.php page. <select name="filter_month" class="filters"> <option>Select a Month</option> <option value="1">January</option> <option value="2">February</optio ...

Sidebar navigation text shifting during transition

I attempted to modify the CSS and JavaScript, but unfortunately, it had no effect and actually caused more issues. I adjusted the position and display properties in the CSS, but it seems that wasn't the root of the problem. If anyone could offer assis ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

A guide on incorporating Google authentication into Vue.js with the use of TypeScript and the component-based syntax

Currently, I am in the process of integrating Google authentication into my Vue.js front end. The project was initialized using CLI with TypeScript and component style syntax enabled, alongside other configurations. Additionally, there is a backend web ser ...

Using AngularJS with the Phonegap Facebook plugin

I am looking to build a Javascript app and deploy it on Android and iOS using Phonegap. My goal is to integrate Facebook login into the app. After exploring the phonegap-facebook plugin, I was able to successfully implement the Facebook login feature. How ...

Combine rows with the same value in the first column of an HTML table

My HTML table has dynamic content, and I need to merge rows in the first column only if their values are identical. You can see an image of the table here. Specifically, if the values in the first column match, those rows should be merged together while le ...

I keep encountering an ENOENT error whenever I try to kick off the project using npm start in Next.js. Can someone help me figure out

Having an issue with Next.js, how can I resolve it? [email protected] start next start ▲ Next.js 14.0.2 Local: http://localhost:3000 [Error: ENOENT: no such file or directory, open 'C:\Users\capas\Desktop\00\React&b ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...