Inject environment variable into SCSS file while using webpack

I'm new to webpack and I need help with reading a specific value, which is the env variable from the webpack.config.js file, in a sass file. This will allow me to have different CSS styles based on the environment.

For example:

  • If the env is set to development, then the color should be green.
  • If the env is set to production, then the color should be blue.

So far, I have been focusing on the sass-loader and trying to pass data, but it hasn't worked. The $env variable is always undefined when I run npm run build:Debug, which runs

webpack --app=all --env=development
.

These are the files I currently have:

webpack.config.js:

const path = require("path");
const common = require("./.webpack/webpack.common.config");

const config = [];

function addAppConfig(app) {
    app.module = common.module;
    app.resolve = common.resolve;
    config.push(app);
}

module.exports = (env, argv) => {
    switch (argv.app) {
        case "a":
            addAppConfig(aa);
            break;

        case "b":
            addAppConfig(bb);
            break;

        case "c":
            addAppConfig(cc);
            break;
        
        default:
        case "all":
            addAppConfig(xyz);
    }

    switch (env) {
        case "local":
            config.forEach(appConfig => {
                appConfig.mode = "development";
                appConfig.output.path = path.resolve(__dirname, "../dist");
                appConfig.output.publicPath = "http://localhost:3000/dist";
                appConfig.devtool = "inline-source-map";
                appConfig.devServer = {
                    contentBase: path.resolve(__dirname, "./public"),
                    port: "3000",
                    watchContentBase: true
                };
            });

            break;

        case "development":
            config.forEach(appConfig => {
                appConfig.mode = "development";
                appConfig.devtool = "inline-source-map";
            });

            break;

        default:
        case "production":
            config.forEach(appConfig => {
                appConfig.mode = "production";
                appConfig.devtool = "cheap-source-map";
            });

            break;
    }

    return config;
};

webpack.common.config.js - this file is used in webpack.config.js:

module.exports = {
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.(s*)css$/,
                use: [
                    {
                        loader: "file-loader",
                        options: {
                            name: "[name].css"
                        }
                    },
                    "extract-loader",
                    "css-loader",
                    "sass-loader"
                ]
            },
            {
                test: /\.(png|jp(e*)g)$/,
                use: [
                    {
                        loader: "url-loader",
                        options: {
                            limit: 8000,
                            name: "images/[name].[ext]"
                        }
                    }
                ]
            },
            {
                test: /\.(svg)$/,
                use: [
                    {
                        loader: "url-loader",
                        options: {
                            limit: 80000,
                            name: "images/[name].[ext]"
                        }
                    }
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf)$/,
                use: [
                    {
                        loader: "url-loader",
                        options: {
                            limit: 8000,
                            name: "fonts/[name].[ext]"
                        }
                    }
                ]
            }
        ]
    },
    resolve: {
        extensions: [".js", ".jsx"]
    }
};

And finally, document.scss:

.aside__left, .aside__right {
    @if $env == 'development' {
        background-color: red; 
      } @else {
        background-color: green;
      }
      background-color: $desiredColor;
}

Is there a way to pass SCSS variables from the webpack config or any other method that allows me to generate different CSS based on the environment?

Answer №2

This particular query has been resolved and the solution provided is accurate, although I had to spend a significant amount of time researching how to use it in a SASS file and connect it with webpack environment. I would like to include this information in my response.

package.json

In the webpack.config.js file, we add the NODE_ENV variable. To include it in the package.json, please refer to: webpackenvironmentconfiguration

"build:dev": "webpack --env.NODE_ENV=dev --config  webpack.config.js --progress",

webpack.config:

Add the desired variables here that you want to utilize based on the environment. For example, if you wish to incorporate the environment into your dynamic URL for a background image.

{
    loader: "sass-loader",
    options: {
        data: "$var1: " + env.NODE_ENV + ";"
    }
}

_variables.scss

You can employ this method in your .sass file in either of the following ways:

$image-url: "https://" + $var1 + ".mysite.net/images/ping.jpg"; or
$image-url: "https://#{$var1}.mysite.net/images/ping.jpg";

Output

The resulting URL will resemble the following:

https://dev.mysite.net/images/ping.jpg

Answer №3

I completely agree with @gorodezkiy's statement. Although, there is a slight distinction in the key name that is no longer data, but rather additionalData (for some time now). Therefore, you can modify your code as follows:

{
    loader: "sass-loader",
    options: {
        additionalData: "$var1: " + yourVar1+ ";"
    }
}

For more information, please visit the following link: https://github.com/webpack-contrib/sass-loader/issues/865

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

Is it possible to change label text using CSS without referencing the element by its ID?

Here is a simple code snippet: <div class="delem"><label class="required" for="last_name">Full Name :</label><input id="fullname" type="text" name="fullname" value="" class="fullsize" required=""></div> <div class="delem" ...

Can a pledge be honored at a precise moment?

I have implemented transitions on my web page. When clicked, everything fades out to an opacity of 0 over a duration of 1 second. Then, a new page is swapped in and everything fades back in to an opacity of 1 over another 1-second duration. The issue aris ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

Can you explain the functionality of the container prop within the Drawer component of material-ui?

While delving into the official documentation for material-ui's Drawer component, I stumbled upon a mysterious container prop that is not explicitly mentioned in the API documentation. Could this possibly be one of the inherent props of a React compon ...

Only make an AJAX request for suggestions with jQuery Autocomplete if the item does not match any data from the previous request

I am currently working with jQuery Autocomplete functionality. The issue I am facing is that it triggers an AJAX request every time a key is pressed, which is not desirable. Ideally, if the data from a previous AJAX request already matches the search query ...

Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code: <template> ...

Guide to sending and receiving JSON data using XAMPP PHP

Currently, my XAMPP 7.1.10-0 server is up and running with the following index.php file: <?php if(isset($_POST["username"])) { echo $_POST; header("Location:getbooks.php"); exit; } else { echo file_get_conten ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Is there a way I can maintain the active state after clicking on a link?

Is there a way to maintain an active element state when navigating to another page after clicking a link? I am wondering if it is possible to use JavaScript to remove the active state from one link and apply it to the next one. I am facing some challenges ...

Dynamic jQuery URL truncater

Is there an on-the-fly URL shortener similar to Tweetdeck available? I have come across several jQuery and JavaScript plugins that can shorten a URL through services like bit.ly when a button is clicked. However, I am looking for one that shortens URLs aut ...

ways to verify ng-if post modification occurrence

Currently, my project is utilizing Angular 6. In the code, there is a div element with *ng-if="edited" as shown below: <div *ngIf="edited"> {{langText}} </div> Initially, when the page loads, edited is set to false and the div is not vis ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

What steps can be taken to prevent a "Flash of Unstyled Content" when using fixed-width cells in CSS Tables?

My website's design is heavily influenced by CSS tables. This decision was made to ensure consistent cell heights regardless of the content, making alignment easier. Overall, this method has been quite effective. However, there is an issue where the ...

What are the steps to integrate MaterializeCss into Vue.js?

I prefer not to utilize Vue-Material or Vuetify. My choice is Materialize. Here's what I do: npm install materialize-css@next In my main.js file, where I define my new Vue App, I import Materialize like this: import 'materialize-css' Th ...

The design I created includes a horizontal scroll feature and certain elements are not properly aligned in the

Oh man, I'm really frustrated right now. I want all my elements to be centered horizontally on smaller devices, but some of them are slightly off to the side. And to top it off, there's a horizontal scroll appearing - it's like something is ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

HTML5 - Ajax - puzzling behavior that I am unable to comprehend

Need Help Clarifying My Issue: I currently have a Div with Page 1 content. Page 1 contains a button that transitions the div content to Page 2. Page 2 has a button that switches the div content back to Page 1. The Problem: If Page 1 is loaded first, t ...

Issue with uploading media on Wordpress: "Unfortunately, an error occurred during the upload process. Please attempt again at a later time."

Often times, when trying to upload media from the front-end, I encounter this issue: An error occurred during the upload process It seems like the error occurs sporadically, making it even more challenging to troubleshoot. Sometimes, when logging in fo ...

How can you create a sophisticated JavaScript object with an intricate design?

In my code, I frequently instantiate an object with the following structure: costs: { totalPerYear, totalEver, perMonth: { items: { depreciation, insurance, credit, inspection, ...

Modifying the title of a webpage with a Bootstrap design

As a newcomer to HTML/CSS, I recently utilized a Bootstrap theme from Themezy to build my personal website. The template includes a navigation bar with tabs labeled Top, Work, Portfolio, and Contact. I felt the need to change Top to About, so I replaced ...