Behemoth
Behemoth

Reputation: 9300

How can I create a global stylesheet to share scss variables in a Nx React project?

Now, I really hope this isn't too opinion based. But I would just love to here some advice since I have no idea how to start this.

I have a basic Nx workspace with a TypeScript React frontend combined with SCSS styles. The project's architecture looks sort of this:

root/
├─ apps/
├─ libs/
│  ├─ someLib1/
│  │  ├─ src/
│  │  │  ├─ lib/
│  │  │  │  ├─ someLib1.tsx
│  │  │  │  ├─ someLib1.scss
│  ├─ someLib2/
│  ├─ someLib3/
│  ├─ shared/
│  │  ├─ styles/
│  │  │  ├─ global.scss

Is there any clever way how I could import global.scss into any accessable (=same folder level or below) component in /libs? To give an example:
Imagine I have declared $example: #fff; in global.scss. How would I use it in someLib1.scss without importing it by the absolute path (@import/@use "../../../shared/styles/global.scss" or @import/@use "/libs/shared/styles/global.scss")?

Upvotes: 5

Views: 5618

Answers (1)

Behemoth
Behemoth

Reputation: 9300

Eventually I came up with the following solution:

I added a custom webpack.config.js file to my workspace and sort of extended the initial config delivered by Nx with an alias of the global.scss file.

const path = require('path');
const nrwlConfig = require('@nrwl/react/plugins/webpack.js');

module.exports = (config) => {
  nrwlConfig(config);

  return {
    ...config,
    resolve: {
      ...config.resolve,
      alias: {
        ...config.resolve.alias,
        'global': path.join(
          __dirname,
          'libs/shared/styles/global.scss'
        ),
      },
    },
  };
};

After doing that I was able to import global.scss in every .scss file in libs by the alias like so:

@import "global";

Upvotes: 5

Related Questions