Search code examples
angularmonoreponrwl-nxnx-monorepo

What is the best way to share SCSS variables between libs and apps in an Angular Nx Monorepo


I'm working on an Angular project structured as a Nx monorepo. The directory structure is as follows:

nx-monorepo-root
│
├── /apps
│  ├── /app1
│  └── /app2
│
├── /libs
│  ├── /shared-ui-lib (Common UI components and variable scss shared between apps)
│      └── src/libs/styles/variable.scss
│  ├── /app1Lib (Specific to app1)
│  ├── /app2Lib (Specific to app2)
│  ├── /prime-ng-lib (Wrapper for PrimeNG components, if needed)
│
├── /package
│  └── /component-lib (Library to be published on npm)
│
├── /tools (Custom scripts or tools for your workspace)
│
├── /node_modules
│
├── /dist (Built output)
│
├── nx.json (Nx configuration)
├── workspace.json (Project configuration)
├── tsconfig.base.json (Base TypeScript configuration)
├── package.json (Root-level dependencies and scripts)

I have a variable.scss file located in shared-ui-lib, which contains various color variables that I want to reuse across multiple components in different libraries and apps.

What I've tried:

Alias in tsconfig.base.json:

"paths": {
  "@styles/*": ["libs/ui/shared-ui-lib/src/lib/styles/*"]
}

stylePreprocessorOptions in project.json:

"options": {
  "stylePreprocessorOptions": {
    "includePaths": [
      "libs/ui/shared-ui-lib/src/lib/styles"
    ]
  }
}

Importing the SCSS file:

@import 'variable';
p {
  color: $primary-color;
}

Issue:

Can't find stylesheet to import.
  ╷
1 │ @import 'variable';
  │         ^^^^^^^^^^^
  ╵
  packages\g99-ui-library\src\lib\components\button\button.component.scss 1:9  root stylesheet

The above import doesn’t work. However, it does work when I use the full relative path like this:

@import 'libs/ui/shared-ui-lib/src/lib/styles/variable.scss';

Question:

What is the best way to share SCSS variables across different apps and libraries in a Nx Angular monorepo? Ideally, I'd like to avoid duplicating imports or code, and I'm open to moving the variable.scss file to the root of the monorepo if necessary. What should be the ideal setup to make this work seamlessly?


Solution

  • Given your folder structure, your stylePreprocessorOptions is wrong.

    I would suggest that (if you use VSCode) you right-click on the styles folder and choose "copy relative path" to have the correct path.

    "libs/ui/shared-ui-lib/src/lib/styles" → Wrong one
    "libs/shared-ui-lib/src/lib/styles" → Correct one
    

    And yes (according to me), the style preprocessor options is the correct way when using a monorepo. If you create a NPM library afterwards, then use assets exports as explained in the documentation.