Stylus Vue Vite: The Trio of Global Variables

I'm trying to figure out how to globally import and use stylus variables in my Vue Vite project. How can I achieve this and access the variables within the script section of my Single File Component (SFC)?

Below is an excerpt from my Vite config:

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  css: {
    preprocessorOptions: {
      styl: {
        additionalData: `@import "@/styles/styles.styl"`
      }
    }
  }
})

Inside my styles.styl file, I define a variable like so:

contentSideMargin = 50px

When attempting to use the style from styles.styl in my SFC as shown below, it doesn't seem to work:

<style lang="stylus" scoped>
#main-container
  padding: $contentSideMargin  /* have also tried `contentSideMargin` */
</style>

Any insights or solutions would be greatly appreciated.

Update: Including my package.json for reference. There are no visible errors, but the variable seems to be passed directly into the CSS rather than its value being applied.

{
  "name": "project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "pinia": "^2.0.17",
    "pug": "^3.0.2",
    "vue": "^3.2.37",
    "vue-router": "^4.1.3"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^3.0.0",
    "stylus": "^0.58.1",
    "stylus-loader": "^7.0.0",
    "vite": "^3.0.0"
  }
}

Answer №1

THE BEST WAY TO SETUP VITE FOR STYLUS USING additionalData PROPERTY

Your search for the perfect solution ends here

vite.config.js:

import { defineConfig } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  css: {
    preprocessorOptions: {
      stylus: {
        additionalData: `@import "${path.resolve(__dirname, 'src/assets/global_variables.styl')}"`
      }
    }
  },
})

A SIMPLER APPROACH - IMPORTING STYLUS VARIABLES IN CSS

If you prefer not to customize how Vite bundles your code, make sure all your

<style lang="stylus" scoped>
include definitions of stylus variables used in the component.

You can either define the variables explicitly at the start of

<style lang="stylus" scoped>
, or import them from a separate file:

App.vue:

<template>
  <div id="my-div">THIS IS MY DIV</div>
</template>
<style lang="stylus" scoped>
@import "./assets/global.styl";

#my-div {
  padding: 1rem;
  color: $c-text;
  background-color: $c-bg;
}
</style>

assets/global.styl:

$c-bg = red
$c-text = yellow

A CUSTOMIZED SETUP - USING A CUSTOM PLUGIN FOR STYLUS WITH VITE:

If you'd rather not use import within your components' <style> tags, set up Vite to automatically inject stylus files into your app's CSS with a custom plugin called vite-stylus-import-plugin.js. This method allows for greater customization of stylus file transformations compared to method A.

vite-stylus-import-plugin.js:

import path from 'path'

export function importStylus() {
    return {
        name: 'vite-stylus-import-plugin',
        async transform(code, id) {
        if (/.stylus$/g.test(id)) {
            return {
            code: `
                @import "${path.resolve(__dirname, 'src/assets/global_variables.styl')}"

                ${code}
            `,
            map: null,
            }
        }
        return null
        }
    }
}

Then use the plugin in your Vite config file:

vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { importStylus } from './vite-stylus-import-plugin.js'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), {
    ...importStylus(),
    enforce: 'pre',
  }]
})

SEE IT IN ACTION

I have demos showcasing the last two methods HERE - Check out the GitHub repo HERE. In the demo, the red <div> was styled using method B, while the blue <div> utilized method C. Although not featured, method A is also functional.

Answer №2

I believe that a better approach would be

contentSideMargin = 50px

...


<style lang="stylus" scoped>
#main-container
  padding: $contentSideMargin  /* have also tried `contentSideMargin` */
</style>

The revised code should look like this

$contentSideMargin = 50px

...


<style lang="stylus" scoped>
#main-container {
  padding: $contentSideMargin;
}
</style>

Credits to @DVN-Anakin for the helpful comment and the provided link (github.com/TOA-Anakin/Vite-Vue3-TS-template) leading to a functional boilerplate - highlighting the noteworthy differences.

In summary: esteemed stackoverflow users - please take note of the comments! Fellow members here make sincere efforts to assist without unnecessary disruptions (hence the comments). Neglecting to acknowledge or thoroughly read them could result in missing crucial information essential for problem-solving (which is essentially our main goal here).

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

Web Security Vulnerability: Cross Site Scripting Detected

In our code, we are aiming to prevent XSS (Cross Site Scripting) attacks. However, the solution may involve a combination of JS (JavaScript) and HTML escaping, which could prove to be quite challenging. Below is a snippet that closely resembles our code: ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

How can I call the telerik radgrid.databind() function using a JavaScript function?

Currently, I am coding in ASP .NET and have an ASPX page featuring a Telerik RadGrid. I am curious to know if it is feasible to call the RadGrid.DataBind() method from within a JavaScript function? ...

The step-by-step guide on passing arguments and fetching results from Angular UI Bootstrap Modal through Components

I am facing a simple scenario where I have defined a modal as a component and opened that modal using `uiModal.open`. However, when I try to pass custom data to the modal using "resolve" in the open method and arguments in the controller constructor, the d ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Bootstrap datetimepicker is not showing the calendar for selecting a date, making it impossible to choose a specific date

I am facing an issue with integrating the bootstrap datetimepicker with Datatables to filter the data based on selected dates. The problem is that only an input bar is displayed on the page, and there is no calendar or calendar symbol visible. I suspect it ...

Generating a file using buffer information in node.js

From the front-end client side, I am sending a file to the server. On the server-side, the data received looks something like this: { name: 'CV-FILIPECOSTA.pdf', data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 6 ...

Exploring the power of ElasticSearch alongside Mysql

As I plan the development of my next app, I am faced with the decision between using NoSQL or a Relational Database. This app will be built using ReactJS and ExpressJS. The data structure includes relational elements like videos with tags and users who li ...

Customize material-ui themes using useStyles / jss

Is it possible to customize the Material-UI theme using styles without relying on !important? const customTheme = createMuiTheme({ overrides: { MuiInputBase: { input: { background: '#dd7711', padding: 10, }, ...

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

Switch up a font style using JavaScript to apply a Google font effect

I am attempting to implement a discreet hidden button on a website that triggers a unique Google font effect for all of the h1 elements displayed on the page. However, I am uncertain about the process and unsure if it is achievable. Below is the code snipp ...

What are some alternatives for integrating React production build files apart from utilizing Express?

Is there a way to integrate React into my library using the HTTP module? I'm trying to figure out how to recursively send static files. Specifically, I want to include the build folder from the React production build, but I'm not sure how to go a ...

Unable to retrieve AJAX response

I've been working on a page where I'm using AJAX to fetch data based on the selection of radio buttons. The three options available are 'Unapproved', 'Approved' and 'All'. My goal is to display the corresponding user ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Is there a way to dynamically insert the value of an input field into a text field in real time using Javascript or ajax?

In my form, there is a text field with the id #image_tag_list_tokens. It looks like this: = f.text_area :tag_list_tokens, label: "Tags (optional) ->", data: {load: @image_tags }, label: "Tags" Additionally, I have an input field and a button: <i ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...