Copy assets of library with Yarn Plug'n'Play

Viewed 626

I have codes to copy assets when building. I'm wondering what's the best way to do the same thing with Yarn Plug'n'Play since node_modules does not exist.

new CopyWebpackPlugin([
  { from: 'node_modules/pdfjs-dist/cmaps/', to: 'static/cmaps/' },
]),

yarn cache dir tells me the directory and also there's a package location in .pnp.js.

  ["pdfjs-dist", new Map([
    ["2.0.943", {
      packageLocation: path.resolve(__dirname, "../../Library/Caches/Yarn/v3/npm-pdfjs-dist-2.0.943-32fb9a2d863df5a1d89521a0b3cd900c16e7edde/node_modules/pdfjs-dist/"),

Should I somehow parse the file and copy as I did before? Or is there better way?

2 Answers

In Yarn Plug n' Play, you can get the base path to your from directory using require.resolve('name-of-package'). In this case, it's something like

const path = require('path');
const modulePath = require.resolve('pdfjs-dist');
const fromPath = path.join(modulePath, 'cmaps');

Using require.resolve is correct, but depending on the package it can result in this error

Error: Qualified path resolution failed: we looked for the following paths, but none could be accessed.

The CopyWebpackPlugin documentation suggests the following snippet when working with yarn workspaces or monorepos.

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: `${path.dirname(
            require.resolve(`${moduleName}/package.json`)
          )}/target`,
          to: "target",
        },
      ],
    }),
  ],
};
Related