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

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

Pass along a parameter to Vue.js within Blade templates in Laravel

Is it possible to send a variable from my PHP Blade template to a Vue component (not a child) in this way? <component param="{{ $param }}"></component> In the Vue.js component: props: ['param'] However, I am consistently receiving ...

Access in-depth data by clicking on a map to get detailed information

Recently, I took on the challenge of managing a golf club website after the original creator had to step away. One urgent issue I need to address is fixing a malfunctioning flash animation that provides information about each hole on the course. My plan is ...

Enhancing the Performance of jQuery Scripts

My jQuery function called textfill is utilized on numerous div elements. Essentially, it resizes the text inside each div to perfectly fit the container so that longer texts are made smaller than shorter ones while maintaining the maximum font size without ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Tips for updating the filename in a file input using AngularJS

Is it possible to dynamically change the name of a chosen file? For instance, if I select a file with the name "img1", can it be automatically changed to a different dynamic name upon selection? <input type="file" fd-input/> ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

Guide to building a customized route using Nuxt

Typically, Nuxt automatically creates a route for each page located in the pages directory. What I would like to achieve is that when a user navigates to a specific page such as project.local/id/ec29cjsa5fas512ik, they are directed to a page template and ...

Unusual occurrence while creating a unique identifier for a React component

I am working on creating a unique identification number for each React component, which will be assigned to the component upon mounting. Here is the approach I am taking: The callOnce function is used to ensure that a specific function is only executed on ...

Try employing an alternative angular controller when working with the bootstrap modal

I am trying to implement a bootstrap modal in my main HTML file, and I need some help on how to call another Angular controller for the modal. The button that triggers the modal is within a div that already has an Angular controller, and this is causing th ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

Infinite loop readiness with JQuery

My current project involves preloading images and seamlessly fading them in once they are fully loaded using JQuery. To achieve this, I attempted to create an invisible image tag where the images would load before setting the source back to the original im ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Using Javascript, you can create a function that can disable or enable a text link based on

Here is the code snippet showcasing CSS styles and HTML elements: CSS: .enableLink{ font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#069; padding-right:20px; text-decoration:underline; cursor:pointer; } .disableLink{ display:none; fon ...

Link embedded in prism formatting, encased in code snippet

In the HTML template, I have the following code snippet: <pre> <code class="language-markup"> {% filter force_escape %} <Item> <MarkUp><a href="http://google.com">Google</a></MarkUp> <No ...

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

The issue with Grid component in Nested Single file Component

I'm currently working on creating a grid component in Vue to set up a sortable and searchable chart using Single File Component. I've also integrated vue-router into the project. Below are my two .vue files. At the moment, I can only see the sear ...

Issue with Braintree drop-in form: Nonce string generation problem

I've encountered a peculiar issue while trying to utilize the dropin form from Braintree. Successfully integrating the form into a view, here's how it looks: <form id="createTransactionForm" method="post" action="#&qu ...

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...