Convert all SASS code into CSS within a Nuxt project

I am currently tackling a project that involves using SASS for part of the code. However, I have made the decision to transition from SASS to vanilla CSS. My goal is to find a way to convert all SASS segments into CSS either programmatically across the entire codebase or at least within individual components as I work on them. Ultimately, I aim to eliminate all SASS dependencies and have only CSS remaining in my code.

Any suggestions or insights on how to achieve this would be greatly appreciated. Thank you in advance!

Edit: The SASS/SCSS sections are written inside component, pages, and layout .vue files within

<style lang="sass">
or
<style lang="scss">
tags. These sections contain imports following the format:

@import './folder/css/stuff';

.head-navigation

Edit 2: Unfortunately, the proposed solution has encountered an error:

Error: Invalid CSS after "@import './folder/css/stuff';": expected 1 selector or at-rule, was ".head-navigation"\n

To see a live example, please click here

Answer №1

Based on your query and provided code snippet, it seems like you are interested in converting only the portion of a vue file that contains sass/scss code. To achieve this task, I would create a custom script that follows these steps:

  1. Iterate through all the .vue files.
  2. Determine if there is a style tag with the language set to sass.
  3. Replace the content with the compiled css code.

In order to execute the above steps, three packages will be utilized:

  • node-sass: Used for converting sass/scss code to css.
  • fs-extra: Employed for file-handling purposes and as an alternative to the native fs module. However, you can stick with the fs module if desired.
  • vue-template-compiler: Serves as a parser specifically designed for understanding Vue components. Although using regular expressions (regex) could have been a feasible option, parsing a language with regex is generally discouraged due to certain computational concepts. For further details, refer to this post.

The following code exemplifies the implementation:

// convert-sass.js
const fs = require('fs-extra');
const path = require('path');
const sass = require('node-sass');
const compiler = require('vue-template-compiler');

const vueDirectory = './src'; // Path to the directory containing .vue files.

function convertSASSinVueFiles(dir) {
  // 1. Iterate over all files within the directory with a .vue extension.
  fs.readdirSync(dir).forEach(file => {
    const filePath = path.join(dir, file);
    if (fs.lstatSync(filePath).isDirectory()) {
      convertSASSinVueFiles(filePath);
    } else if (path.extname(file) === '.vue') {
      convertSASSinVueComponent(filePath);
    }
  });
}
function convertSASSinVueComponent(file) {

  const content = fs.readFileSync(file, 'utf8');
  // Parse the Vue file.
  const parsedComponent = compiler.parseComponent(content);
  /* 2. Check for a style tag with lang attribute set to sass.
        Adjustments may be made based on requirements. */
  if (parsedComponent.styles.length > 0 && 
        (parsedComponent.styles[0].lang === 'sass' ||
         parsedComponent.styles[0].lang === 'scss')) {
    const sassCode = parsedComponent.styles[0].content;
    // Convert sass code to css.
    const cssCode = sass.renderSync(
      {
        data: sassCode,
        includePaths: ['./path/to/your/partials']
      }
    ).css.toString();
    // Replace sass content with css code.
    const updatedContent = content.
                             replace(/<style.*lang="s[ac]ss".*>([\s\S]*?)<\/style>/, 
                              `<style>${cssCode}</style>`);
    fs.writeFileSync(file, updatedContent);
  }
}
convertSASSinVueFiles(vueDirectory);

NOTE 1: The current replace regex, i.e.,

/<style.*lang="s[ac]ss".*>([\s\S]*?)<\/style>/
, accommodates both scss and sass syntaxes. Modifications can be made according to specific needs.

NOTE 2: When utilizing partials, ensure inclusion of one of the properties offered by the scss-compiler, such as the includePaths option.

EDIT:

Initially, the provided code covered conversion from .scss to .css syntax. However, considering recent feedback highlighting usage of .sass syntax instead of .scss, adjustments need to be made. Refer to this post for insights on the differences between their syntaxes. Notably, one employs indentation while the other utilizes curly braces similar to CSS rules.

Fortunately, there exists a single compiler capable of handling both syntaxes, as initially utilized. Simply incorporate an additional option, indentedSyntax, to the renderSync() function and set its value to true:

const isSass = parsedComponent.styles[0].lang === 'sass';
const cssCode = sass.renderSync(
    {
      data: sassCode,
      includePaths: ['./path/to/your/partials'],
      indentedSyntax: isSass // Enable for sass syntax
    }
  ).css.toString();

NOTE 3: Consider adjusting the partials paths within the includePaths option to align with project requirements. If specified, the compiler will search within the designated directory for partials, disregarding relative paths inside your @import rule. To illustrate, providing ./src/sass in the array of includePaths and importing a partial as

@import './src/sass/someDir/typography';
might trigger a file not found error. In such cases, omitting the includePaths option from the script could be beneficial.

CODE DEMO

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 there a way to dynamically include an attribute using VueJS?

Is there a way in Vue to dynamically add an attribute, not just the value of an attribute using v-bind? I am aware that I can set a value to an attribute dynamically with v-bind, but I would like to add the attribute itself based on a condition. Something ...

Enhance your VUEX data model using Computed mapGetters

I'm just getting started with Vuex and I'm attempting to update the card's imageURL property from the data model every time a computed getter is updated. The getter is successfully updating as I can see changes reflected in the HTML of the ...

What are some ways to make source code more visually appealing on an HTML/JSP page as it is being

I've recently created a webpage with some Java source code, neatly organized within blocks. However, I'm looking to enhance its appearance so it truly looks like Java code. Take a look at my page's code here for reference: Are there any onl ...

Utilize vue.js to cache and stream videos

I'm new to the world of vue.js and I'm facing a certain dilemma. I implemented a caching system using resource-loader that preloads my images and videos and stores the data in an array. Everything is functioning correctly, but now I'm unsur ...

Is there a way to adjust the image dimensions when clicked and then revert it to its original size using JavaScript?

Is there a way to make an image in an HTML file change size by 50% and then toggle back to its normal size on a second click using JavaScript? I've attempted to do it similar to the onmouseover function, but it doesn't seem to be working. Any sug ...

Exploring the functionality of Jquery with the :active selector

Here is the code I have been working on: $('#ss a:active').parent().addClass('ss-active'); It seems like my code is not functioning as expected. Can you help me figure out how to achieve my desired outcome? Additionally, I want the bu ...

html issue with the footer

Just starting out with HTML and encountering some difficulties with adding a footer. The main issue is that when I add the footer, the 'form' element gets stretched all the way down until it reaches the footer - you can see an example of this her ...

What are the steps to start using the Intersection Observer API right away?

Utilizing the Intersection Observer API, I can accurately determine whether an element is within the viewport or not. Is there a way to utilize the Intersection Observer API to detect if an element is in the viewport without relying on a callback function ...

Tips for retrieving data from an Excel spreadsheet on an HTML/CSS webpage

I have a single HTML template at this location: . The current page is tailored for the state of Arkansas in the US, but I now need to replicate the design for all 50 states. Each state page will have the same layout, but different content specific to that ...

Different boolean variable assigned to every item in v-for loop

I am working on creating a custom play/pause button for my audio elements, and here is how I have implemented it: <div v-for="(post, p) in post_list"> <!-- ... --> <!-- ... --> <!-- ... --> <v-avatar v-i ...

I seem to be having trouble with my dropdown menu, can anyone help me figure out what I might be doing wrong

I'm new to web development and I'm trying to create a dropdown menu. The issue is that when I hover over a specific element, it takes up more space than expected. My goal is for it to appear below the "shop" element. I'm not sure where I&a ...

Is There a Glitch in IE9? Unexplained Expansion of DIV Element

Here is a small code sample that I have: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Test</title> <style type="text/css"> table.Sample { width: 600px; table-layout: fixed; } table.Sample ...

Maintain the proportion of the browser window when reducing its size

<html> <head> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <img src="spacer--1200x800.png" width="1200" height="800" /> </body> </html> This section contains CSS ...

Creating a PDF from slides using tools like mkd2pdf or wkhtmltopdf has never been easier. This

I am exploring the possibility of creating PDF files using mkd2pdf, a tool based on wkhtmltopdf. Mkd2pdf has the ability to generate PDFs from markdown content and utilizes a CSS file for styling purposes. For example: h1 { page-break-before: always; } ...

Tips for addressing the issue of mat-list-item not occupying the entire row's space

Hello everyone, I am currently trying to render an article.component.html within my article-list-component.html in a list format. When I use plain HTML, it renders correctly as shown in picture 1: Title - author - Date Here is the code for my article-list. ...

Tips for utilizing the data-target feature in Bootstrap?

<button id="btn-id" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#bs-navbar-collapse-1"> <span class="navbar-toggler-icon"></span> <span c ...

Unable to conceal the scrollbar while keeping the div scrollable

I've been attempting to implement the techniques outlined in the guides on this site, but I'm encountering difficulty hiding the scroll bar while still maintaining scrolling functionality! My current approach involves setting the parent as relat ...

What is the method for adjusting the font size of the label in an Angular mat-checkbox element?

I've been trying to adjust the font size of a mat-checkbox's label, but no matter what I do, the component's default styles keep overriding my changes: Using !important Trying ::ng-deep Applying a global style in styles.scss <mat-checkb ...

Guide on aligning a series of divs in a single row within a parent div

Within the confines of a 400px wide div called "container", there are six left-floated "box" divs, each 100px wide. The combined width of the "box" divs exceeds 400px, resulting in the divs wrapping onto two lines, with 4 on the first and 2 on the second ...

Mobile device causing issues with Bootstrap navbar toggler functionality

I am having an issue with my Bootstrap 5 navbar. It is not functioning properly on mobile devices. When I click the toggle button, nothing happens. <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="contai ...