Search code examples
yarnpkgyarn-v2

How to include css files using yarn pnp


Ive created a new project and used yarn to install reset-css and sass package. In my main stylesheet I now want to include the reset.css stylesheet from the installed package and build it with sass.

How can I locate where reset-css file is to get its path and how can I @use/@import it in my scss file?

Normally I could just reference it from node_modules but the folder does not exist anymore when using yarn pnp.


Solution

  • When using Yarn Plug'n'Play (PnP), traditional disk-based node_modules directories are not created. Instead, Yarn manages the dependency resolution in-memory or via zip files, bypassing the need for these directories. But this new architecture poses a question: how do you refer to installed packages without a disk-based file path?

    In Yarn PnP, you can typically import dependencies in your JavaScript files as you would normally, but for cases like CSS, it can be a bit tricky.

    Here are some suggestions for importing reset-css in a Sass/SCSS file when using Yarn PnP:

    Method 1: resolutions in package.json

    1. Add reset-css to your package.json if you haven't already.

      {
        "dependencies": {
          "reset-css": "^x.y.z"
        }
      }
      
    2. Run yarn install.

    3. Use Yarn's resolutions field to create a symlink that you can reference in your Sass file.

      {
        "dependencies": {
          "reset-css": "^x.y.z"
        },
        "resolutions": {
          "**/reset-css": "portal:./path/to/symlink/reset-css"
        }
      }
      
    4. In your Sass/SCSS file:

      @import "./path/to/symlink/reset-css/reset.css";
      

    Method 2: sass includePaths Option

    1. When you are running sass or using a build tool that uses sass (like Webpack's sass-loader), you can specify includePaths to include the Yarn cache directory.

      For example, in Webpack config:

      {
        test: /\.scss$/,
        use: [{
          loader: 'sass-loader',
          options: {
            sassOptions: {
              includePaths: [path.resolve(__dirname, '.yarn/cache')],
            },
          },
        }]
      }
      
    2. Then, you should be able to import reset-css in your .scss file like this:

      @import "reset-css/reset.css";
      

    Method 3: Copy During Build

    You could copy the reset.css into your source directory during a build step. The idea is to use build tooling to locate the file within the Yarn cache and copy it into your project so that it can be easily referenced.

    1. Identify the package location in the Yarn cache.
    2. Use build tools like Webpack or a script to copy the reset.css into your project directory.
    3. Reference it like any other local stylesheet.

    Choose the method that best suits your project structure and build process.