Instructions for converting SCSS to CSS and storing the CSS code as a string in a variable

I am currently developing a Single Page Application (SPA) using Vue (specifically Quasar), and I have the following requirements:

  • Load the contents of a CSS file into a JavaScript variable or Vue data property dynamically
  • The CSS file should be generated from a SCSS file at build time

Instead of loading a pre-made CSS file, I want to write the CSS code using SASS. Additionally, I do not want to compile the CSS from SCSS each time the app loads.

Here is what I have in mind for the workflow:

  • Create the CSS in a specific SCSS file within my project structure
  • Compile this SCSS file into a CSS file during build time or run-dev time
  • Then, in one of my Vue components, load the resulting CSS code as a string into a variable at runtime

The purpose of this setup is to pass the CSS code into an iframe using postMessage and have the iframe apply the styles to the page using CSSStyleSheet's insertRule() method.

What steps should I take to configure my project and packages to achieve this? It seems like I may need to use the raw-loader, but how can I ensure that the CSS file is prepared correctly during the project build so that the raw-loader can access it at runtime?

Answer №1

Upon initial evaluation, it appears that there are two issues present here, both of which can be resolved quite easily.

The first problem is the absence of a scss compiler plugin in your project's build process. Depending on your existing toolset, you may need to choose a suitable compiler plugin. Alternatively, you can directly integrate https://www.npmjs.com/package/node-sass

The second challenge involves handling CSS at runtime. There are multiple approaches available for this task. You can either compile the CSS file into your bundle or fetch it dynamically during runtime. The latter option would keep your bundle size minimal and allow for regular CSS serving, albeit requiring a server. On the other hand, compiling at build time would result in faster initial loading but increase overall bundle size.

If you are utilizing webpack, you may consider using the raw loader as suggested; however, if webpack is not part of your current setup, this method may not be applicable.

To avoid runtime loading, you could implement an additional build step to convert the CSS into a String literal, eliminating the need for dynamic retrieval but potentially enlarging the bundle size.

For runtime loading, fetching the file via AJAX from an HTTP server is a straightforward solution.

Answer №2

I have come up with a solution that worked for me:

  1. First step is to download and install the "raw-loader" loader
  2. Next, import the SCSS file by using the code below:

    import style from '!raw-loader!sass-loader!./my-styles.scss'

It's important to note that the exclamation mark at the beginning of the import statement is used to override the default loaders configuration. In my situation, Quasar was automatically chaining the "style-loader" for SCSS files which I had to disable in order to get this to work.

After completing these steps, you should now have access to the compiled CSS code stored in the style variable.

Answer №3

To begin, execute the following command.

npm install path sass

After completing that step...

const path = require("path");
const sass = require("sass");

const css = sass.compile(path.join(__dirname, "style.scss")).css;
console.log(css);

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

What methods are available for incorporating JavaScript classes from separate files into HTML while maintaining compatibility with IOS?

Currently, I find myself in a situation where I am required to utilize classes from JavaScript across various js files. For instance, there is a class named Panel located within the file js/radar-home.js. Below is how I am currently utilizing the class wit ...

What is the easiest way to access my JSON data within my script?

My file structure looks like this app/ index.html script.js data.json Does that make sense? Now, I want to randomly select an object from my JSON data and display it to the user each time the document loads. However, I'm facing an issue with e ...

Unleashing the power of jQuery ajax without requiring a server

I've been incorporating jQuery ajax calls on my HTML pages. $.ajax({ url: 'search/' + page + '.html', dataType: 'text', success: function(data) { $(".searchData").html(data); $(".searchData"). ...

The function parameter in Angular's ngModelChange behaves differently than $event

How can I pass a different parameter to the $event in the function? <div class='col-sm'> <label class="col-3 col-form-label">Origen</label> <div class="col-4"> <select ...

How can we generate an array of duplicated values from an array that already contains duplicates in JavaScript?

Given an array of objects like ["a","b","a","c","d","b"], how can I efficiently retrieve an array of the duplicate elements, such as ["a","b"]? Is there a method similar to u ...

Generating and assembling text with vue.js

One of the requirements states that all HTML elements must be defined in a JSON file and utilized within the template. In order to meet this requirement, there is a function called "markComplete" that should be triggered whenever a checkbox is changed. S ...

Creating a customized filter for a dropdown in the v-data-table component of Vuetify

In my v-data-table, I have already enabled the :search and :sort-by options. Now, I have added a select element that pulls in status values from VueX - Accepted or Rejected. My goal is to filter the table to display only the accepted values when selected f ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Leveraging an array retrieved through JQuery AJAX for auto-complete data in materializecss

I am delving into materializecss for the first time, aiming to enhance its auto complete feature by incorporating an array of options obtained from a database. Unfortunately, my attempts have not been successful. After scouring through Stack Overflow and o ...

Jquery bypasses original stylesheet settings when inline styles are removed

I have a CSS file with various styles defined within it. One style in particular has the property position set to 'fixed', but this only applies to specific combinations of classes. For example: .mystyle.blue { position: fixed; } Here, el ...

The buttons mysteriously vanish when hovered over in Internet Explorer 11

I've encountered a strange issue with my website www.webfounded.com when viewed in Internet Explorer - all of my bootstrap buttons disappear on hover! Despite adding CSS classes for multiple browser compatibility and even attempting to remove the hove ...

Storing and retrieving a client-side object in Javascript: A step-by-step guide

Novice inquiry: I have created a basic draggable to-do list that saves its state in a single object containing tasks, containers, and index - currently, it is being stored in local storage. I am now delving into server-side development using express and ...

Update only one field at a time using the REST API

Currently, I am developing an inline grid editor that triggers a call to an express rest api whenever a user updates a single value in the grid. The issue I am facing is that when a field is changed, my PATCH request attempts to update all fields instead o ...

Eliminating single and multiple relationships - Mongoose

My Assignment schema includes references to both Groups and Projects. Assignment == Group [One-One Relationship] Assignment == Projects [One-Many Relationship] Here is my Assignment Schema: var AssignmentSchema = new Schema({ name: String, group ...

Activating a link click inside a table with jquery

I have been attempting to trigger a click on an anchor within the table compareTable with the code below, however it does not appear to be working as expected. Would anyone be able to provide insight into a possible solution? $('#compareTable a' ...

Transform time-consuming tasks into asynchronous operations

How can a time-consuming function, like image manipulation, be executed asynchronously to enable other code to run simultaneously or to allow multiple instances of the same function to run in parallel? (specifically in Node.js) One example could be using ...

Coordinates of HTML elements corners after rotation

Seeking to obtain the XY coordinates of an HTML element in order to accurately calculate the physical distance, in pixels, from the corners of a rotated element relative to another element. In this code snippet, I am attempting to determine the distance f ...

Eliminate the listener if the connected function contains a binding

Here is a code snippet to consider: class Test { constructor() { this.breakpoints = {}; } add(options) { // Register the media query this.breakpoints[options.breakpoint] = window.matchMedia(options.breakpoint); ...

What is the best method to ensure a jQuery function only runs once, even when declared multiple times within a form?

Whenever a button with a specific class is clicked in a document, a jQuery function is triggered to perform a certain action. See example below. $(document).on('click', '.tambah', function(){ alert('tombol tambah telah ditekan ...

Navigating using Vue Router: Automatically redirect to the homepage if the user is trying to reload a subpage

How can I redirect to the root of my Vue application when a user reloads a subpage in order to perform some initialization work? Below is my current routing setup: const routes: RouteRecordRaw[] = [ { path: '/', component: HeaderLayout ...