Custom TailwindCSS Theme Builder

My goal is to implement a variation of themes and be able to switch between them using tailwind CSS. I came across a tutorial on YouTube regarding this topic in JavaScript youtube video, but I am working with TypeScript and encountering issues with a custom function called with opacity. When using this function, the color does not display properly. However, if we pass a variable directly instead of using the custom function to apply opacity, it works correctly.

global.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --primary-color: #847869;
    --secondary-color: #fae1c3;

    --primary-background-color: #202020;
    --secondary-background-color: #1d1d1d;
    --accentColor: #91170c;

    --robotoMono: "Roboto Mono", monospace;
    --barlow: "Barlow", sans-serif;
  }
}

html {
  scroll-behavior: smooth;
}

.container {
  width: 50%;
  margin: 0 auto;
}
tailwind.config.ts

import { type Config } from "tailwindcss";
import { fontFamily } from "tailwindcss/defaultTheme";

function withOpacity(variableName: string) {
  return ({ opacityValue }: { opacityValue: number | undefined }): string => {
    if (opacityValue !== undefined) {
      return `rgba(var(${variableName}), ${opacityValue})`;
    }
    return `rgb(var(${variableName}))`;
  };
}

export default {
  content: ["./src/**/*.tsx"],
  theme: {
    extend: {
      fontFamily: {
        sans: ["var(--font-sans)", ...fontFamily.sans],
      },
      textColor: {
        skin: {
          base: "var( --primary-color)",
          // muted: withOpacity('--color-text-muted'),
          // inverted: withOpacity('--color-text-inverted'),
        },
      },
      backgroundColor: {
        skin: {
          withOpacity("--primary-background-color")
          // fill: withOpacity("--primary-background-color") as unknown as string,
          // 'button-accent': withOpacity('--color-button-accent'),
          // 'button-accent-hover': withOpacity('--color-button-accent-hover'),
          // 'button-muted': withOpacity('--color-button-muted'),
        },
      },
      gradientColorStops: {
        skin: {
          // hue: withOpacity('--color-fill'),
        },
      },
    },
  },
  plugins: [],
} satisfies Config;
Type '(: any) => any' is not assignable to type 'string | RecursiveKeyValuePair<string, string>'.ts(2322)
⨯ ./src/styles/globals.css.webpack[javascript/auto]!=!./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[12].oneOf[12].use[2]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[12].oneOf[12].use[3]!./src/styles/globals.css
SyntaxError: Unexpected token (29:23)
Import trace for requested module:
./src/styles/globals.css.webpack[javascript/auto]!=!./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[12].oneOf[12].use[2]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[12].oneOf[12].use[3]!./src/styles/globals.css
./src/styles/globals.css

Answer №1

The initial step is to set the return type for the opacity custom function. Moreover, within the backgroundColor property, the skin should be structured as a key value pair. Here's an example:

function withOpacity(variableName: string): string {
  return ({ opacityValue }: { opacityValue: number | undefined }): string => {
    if (opacityValue !== undefined) {
      return `rgba(var(${variableName}), ${opacityValue})`;
    }
    return `rgb(var(${variableName}))`;
  };
}

export default {
  content: ["./src/**/*.tsx"],
  theme: {
    extend: {
      fontFamily: {
        sans: ["var(--font-sans)", ...fontFamily.sans],
      },
      textColor: {
        skin: {
          base: "var( --primary-color)",
          // muted: withOpacity('--color-text-muted'),
          // inverted: withOpacity('--color-text-inverted'),
        },
      },
      backgroundColor: {
        skin: {
          main: withOpacity("--primary-background-color")
          // fill: withOpacity("--primary-background-color") as unknown as string,
          // 'button-accent': withOpacity('--color-button-accent'),
          // 'button-accent-hover': withOpacity('--color-button-accent-hover'),
          // 'button-muted': withOpacity('--color-button-muted'),
        },
      },
      gradientColorStops: {
        skin: {
          // hue: withOpacity('--color-fill'),
        },
      },
    },
  },
  plugins: [],
} satisfies Config;

You may refer to this repository for more information https://gist.github.com/vladdu/88f0c032fbca4ccca3456e92de7b80a7

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

Tips for sending context in the success callback function of a jQuery AJAX request

const Box = function(){ this.parameters = {name:"rajakvk", year:2010}; Box.prototype.callJsp = function() { $.ajax({ type: "post", url: "some url", success: this.executeSuccess.bind(this), err ...

When I use Input.value, it seems to cause a strange lag in my console.log

My goal is to have a text input on the page that triggers #fourChord's text to change as I type characters into the input. The issue I am facing is that console.log registers my input, but the first character is always ignored. For example, if I type ...

Click to slide the div down and up when needed

Currently, I am utilizing the code below to implement a slide up/down effect on a div using JavaScript. The slide down action is triggered by a button, while the slide up action is associated with a close text. My goal is to have the button toggle betwee ...

Order a array of JSON by time, showing it in a 12-hour format

I've come across a JSON structure that looks like this: [ { "Event_code": "AB-001", "Start_time": "11:00 AM", "End_time": "3:00 PM", "Session_type": "Tour" }, { "Event_code": "AB-002", "Start_time": "09:30 AM", "End_ ...

Options for Printing HTML - Explore Different Techniques for Creating HTML Printouts and Weigh the Advantages and Disadvantages

As I work on maintaining an application, I am faced with the task of printing out a report. However, my curiosity extends beyond this assignment as I wonder about the various ways to format an HTML page for optimal printing results and the advantages and d ...

Issue with Bootstrap 5 grid system, div falling down

I'm having some trouble with my HTML code here. <div style="height: 100px;" class="col-6 bg-success mt-40 d-inline-block">1</div> <div style="height: 100px;" class="col-6 bg-success mt-40 d-inline-bloc ...

To streamline your shopping experience, simply input various product IDs into the designated textbox to add multiple items to your shopping

I am currently working on a feature for Magento that allows customers to input multiple product IDs in a text box and add them to their shopping cart. I have successfully implemented this functionality for a single product ID using the jQuery code below: ...

Issue with loading 3D model using three.js in a web browser

While using ASP.Net core, I encountered an issue with loading a 3D model using the Three.js library. The error message "ERR_NAME_NOT_RESOLVED" appears when trying to load the scene. You can view the code in my VS View here. This code works perfectly in VS ...

Conceal the block quotes while substituting with a newline

My HTML page contains numerous comments enclosed in blockquotes. I attempted to implement a feature that allows users to hide all the comments with just one click by using the following JavaScript code: const blockQuotes = document.getElementsByTagName(& ...

Saving an "Online User Registry" for a messaging platform (PHP/AJAX)

In my setup, I manage multiple chat rooms by storing the list of chat users in a PHP variable. As users join or leave a room, their names are added to or removed from this list. To ensure data persistence, I rely on memcached. Periodical AJAX requests are ...

What is the best approach for managing caching effectively?

My SPA application is built using Websocket, Polymer, ES6, and HTML5. It is hosted on a Jetty 9 backend bundled as a runnable JAR with all resources inside. I want to implement a feature where upon deploying a new version of the JAR, I can send a message ...

Am I using the if statement correctly?

Can someone confirm if I am using the if statement correctly in this script? Or is it not possible to use an if statement within this code? <script type="text/javascript" charset="utf-8"> $(document).ready(function () { $('#customerTable&ap ...

Blending synchronous and asynchronous testing with Mocha

There is a function that calculates certain values and informs the user about events using callbacks: function returnAndCallback(callback) { callback(5); // not always called return 3; } Incorporating Mocha and Should.js, a test was created: descri ...

Error: The 'length' property of the twitter object is not defined and cannot be read

I am trying to fetch data from my Twitter account using PHP and JSON. My PHP code is working fine, but I am facing an error with jQuery. Uncaught TypeError: Cannot read property 'length' of undefined $(document).ready(function() { var dm ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

Should the max-height transition be set from 0 to automatically adjust or to none?

I'm dealing with an element that has a max-height of 0, and I want to smoothly transition it to either no max-height, auto, or none; essentially allowing it to expand based on the number of elements inside. I prefer not to use JavaScript or flex at th ...

What is the best way to align the plain text to the exact same level as the text inside a text box in Internet Explorer

I am trying to get the text 'Start new Search' to align at the same height as the text in the input box. This issue is only occurring in IE7. Below you can find the image, HTML, and CSS related to this problem: <span class="search_new_search_ ...

Encountering an issue with PrimeNG's <p-calendar> component: the error message "date

I encountered an issue resulting in the following error message: core.es5.js:1020 ERROR Error: Uncaught (in promise): TypeError: date.getMonth is not a function TypeError: date.getMonth is not a function This error occurs whenever I attempt to implement ...

Position card action buttons at the bottom using Material UI

I have been working on an app using ReactJS and incorporating MaterialUI (for React) along with React Flexbox. One issue I've encountered is the struggle to position the card buttons at the bottom, which seems to be a common problem across different ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...