What is the correct way to link to a SCSS file within a component's directory?

The structure of my directories is as follows:

stylesheets
..modules
...._all.scss
...._colors.scss
..partials
...._all.scss
...._Home.scss
..main.scss

In the _Home.scss file, I have the following:

@import '../modules/all';

.headerStyle {
  color: pink;
  font-size: 15;
  font-weight: 500;
}

In the main.scss file, I import all the _all.scss files in the stylesheets folder like this:

@import 'modules/all'
@import 'partials/all'

html { font-family: 'Roboto', sans-serif; }
body {
  margin: 0;
  background-color: orange
}

When importing the stylesheet in my component, I simply do:

import '../../stylesheets/main.scss'

...

<div className="headerStyle">Header</div>

However, the .headerStyle styling from _Home.scss is not being applied to the <div> in the component. I have verified the directory path to main.scss and there are no errors present.

Currently, only the styles applied in the body block are being displayed:

body {
  margin: 0;
  background-color: orange
}

What could I possibly be doing wrong? Is there a more effective way to import stylesheets into a component without having to redefine it each time for a component?

Thank you in advance for your assistance, and I appreciate any help given.

Answer №1

My successful experience involved using plain HTML along with the Scout-App to convert SCSS to CSS:

Just to add, although I am new to React, I found a helpful post on hugogiraudel.com that suggests the syntax is quite similar to what I used.

Having recently started using SCSS myself, I noticed only a few minor typos in your code example. Assuming the 'body' styling is working, it seems the import statement in your React component is correct.

For a different approach to component imports, I suggest referring to the blog post and the corresponding Github repository mentioned by the author.

Here is the directory structure I followed:

- project_folder
    - index.html
    - stylesheets
        - main.scss
        - partials
            - _all.scss
            - _Home.scss

In index.html:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <!-- Note: 'css_stylesheets' is the folder where the 
                   Scout-App added the transformed CSS files -->
        <link rel="stylesheet" href="css_stylesheets/main.css" type="text/css" />
    </head>
    <body>
        <!-- Note: In HTML, the attribute is 'class' not 'className'
                   Edit 3: 'className' is correct, my mistake -->
        <div class="headerStyle">Header</div>
    </body>
</html>

In stylesheets/main.scss:

@import 'partials/all'; // You seem to be missing a semicolon (;) here

html { font-family: 'Roboto', sans-serif; }
body {
  margin: 0;
  background-color: orange; // It's optional, but I added it
}

In stylesheets/partials/_all.scss:

@import '_Home.scss';

In stylesheets/partials/_Home.scss:

.headerStyle {
  color: pink;
  font-size: 30px; // Added 'px' for Firefox compatibility
  font-weight: 500;
}

Answer №2

Your Webpack setup is set to utilize the stylesheets directory, enabling you to simply use

import 'main.scss'

rather than

import '../../stylesheets/main.scss'

Answer №3

@fingerpich provided a clever solution for simplifying your paths. By setting up an alias to your stylesheets directory, you can always import relative to that directory:

Here is how you can configure Webpack:

{
  resolve: {
    alias: {
      // Make sure the path resolves relative to the files where you're importing them
      stylesheets: path.resolve(__dirname, '../stylesheets')
    }
  }
}

Check out the documentation for more information:

In your component file, you can now simply import like this:

import 'stylesheets/main.scss'

Additionally, you can make webpack resolve imports from inside your sass files by adding ~ to the front of the path. This allows you to write your imports just like in your component files, and they will resolve to your alias:

@import '~stylesheets/modules/_colors.scss'

Refer to the documentation for more details: https://github.com/jtangelder/sass-loader#imports

Answer №4

The code you provided is almost complete, with only one missing detail: the semi-colon(;) When using SCSS, it's important to remember to use semi-colons to end each statement.

Here is the revised code:

@import 'modules/all';
@import 'partials/all';

html { font-family: 'Roboto', sans-serif; }
body {
  margin: 0;
  background-color: orange;
}

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

Struggling to get my chart to render dynamically in vue-chartjs

In my MainChart.vue file, I defined my chart like this: import { Line, mixins } from 'vue-chartjs' const { reactiveProp } = mixins // const brandPrimary = '#20a8d8' export default { extends: Line, mixins: [reactiveProp], props: [& ...

Unlock the potential of Vue custom props within the asyncData function in your nuxtjs project!

I have a special function in my project that serves as a plugin import Vue from 'vue' function duplicateText(text) { var input = document.createElement('input'); input.setAttribute('value', text); document.body.a ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...

Transforming a string to a Date object using JavaScript

Can someone assist me in converting a PHP timestamp into a JavaScript Date() object? This is the PHP code I use to get the timestamp: $timestart = time(); I need help converting this timestamp into a JavaScript date object. The concept of working with d ...

It appears that the validation and onChange event handler in Material-UI's TextField are not functioning as anticipated

Currently, I am working with React and Material-UI's TextField component using type='number'. The default validation provided seems quite simple, allowing any character that could potentially represent part of a number [0-9\.eE-]*. This ...

Chart rendering failure: unable to obtain context from the provided item

I am encountering an issue while trying to incorporate a chart from the charts.js library into my Vue.js and Vuetify application. The error message that keeps popping up is: Failed to create chart: can't acquire context from the given item Even af ...

Utilize dynamic tags to implement filters

Currently, I am working on a project where I have a table displaying elements using ng-repeat. My goal is to implement dynamic filters that can be added through tags using ng-tags-input plugin. These tags will serve as the filter criteria for the table dat ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...

The system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

How can we modify the elements within an Object tag in HTML? If it is achievable, what is the process?

I am working on a project involving an HTML page that includes content from an external website using an HTML object tag as shown below: <object data="someUrl-on-different-domain-than-host" type="text/html"></object> My goal is to use jQuery ...

Vue: restrict entry to the view unless props are configured

Currently, I am in the process of creating a Vue game that consists of two main views: a 'setup' view and a 'play' view. The values that are configured in the setup view are then passed as props to the play view, initiating the game wit ...

I'm wondering why my typography components display correctly on my local host, but not on my aws server. Any insights on

I've encountered an issue with the typography component I'm using for my headings. When I publish the website, the headings do not render properly and the styles are not applied correctly. Strangely, everything looks fine during npm run dev, but ...

Accelerate website loading

After testing the speed of my site's loading, I discovered that the reason for its slow speed is... Some proxy caching servers do not cache resources with a "?" in the URL. To address this issue, it is recommended to remove the query string and enc ...

Having trouble navigating the dependency graph: Unable to locate module './crypto_auth' in sodium-universal

Encountering the following error while trying to browserify a node project from https://github.com/datproject/sdk: Error: Can't walk dependency graph: Cannot find module './crypto_auth' from 'C:\myPath\node_modules\sodium ...

Filtering JSON data by date range in React JS

I have a dataset with JSON data containing ISO dates, and my goal is to filter out entries based on the "date_created" field falling within a specific date range. The time component should be ignored in this comparison, and the original JSON data should re ...

Struggling with integrating HTML Canvas within Vue.js

Currently, I am attempting to upload an image by utilizing HTML canvas. My decision to use canvas stems from the fact that I will be superimposing additional images based on the data received from the API, and this process seems more straightforward when u ...

Clearing values in a Redux form

I am using Redux to toggle the visibility of components based on a value. I want to reset values when switching between options. How can I clear state values when switching between fields that are being hidden or shown? What is the best approach for vali ...

Displaying posts in a WordPress loop with a unique and unconventional CSS design

My issue with the WordPress loop is that the posts are displaying oddly. Originally, when I had 3 posts, they appeared inline as expected. However, now that I have 5 posts, they are showing up in a strange way (refer to the image linked below). The arrow i ...

Effective ways to send children and type to the classnames library while using Next.js

I am currently learning Nextjs and following the tutorial found at this link. In order to utilize the classnames library, I have created a module called "alert.js". import styles from './alert.module.css' import cn from 'classnames' e ...

Tips for storing the outcome of a MySQL query in ReactJs?

I am working on a ReactJs code where I have a SELECT statement. The request is functioning correctly, but now I want to store the result into a variable. How can I achieve this? let result; async function fetchSubsystems() { return Axios ...