Using copy-webpack-plugin returns an error

Viewed 2865

I am trying to copy an asset folder from src to dist and I cant get this to work. In my webpack config I have:

const CopyPlugin = require("copy-webpack-plugin");

const images = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { 
          from: 'src/assets/*',
          to: 'dist/assets/*'
        },
      ],
    }),
  ]
};

module.exports = [
  images
];

but it gives me this error:

ERROR in main
Module not found: Error: Can't resolve './src'

I have "copy-webpack-plugin": "^9.0.1", and "webpack": "^5.47.0", "webpack-cli": "^4.7.2" in my package file.

2 Answers

According to this issue, you are likely using a version of Webpack that copy-webpack-plugin doesn't support.

... you need webpack@5 for latest version.

Assuming you are on Webpack 4, you have two options:

  1. Upgrade to webpack@5.x, which copy-webpack-plugin@8.x supports.
  2. Downgrade to copy-webpack-plugin@6.x, which is the last version that supports webpack@4.x.

The default webpack configuration makes some assumptions about the environment it is executed in. If nothing else is configured, it makes several attempts to find an entry (starting) point for the build process. Among others, it looks for a file named index.js in the src folder. The file itself can be empty. So you should simply create this empty file in src, and the error will disappear.

Additionally, the CopyPlugin should be configured like this:

patterns: [
        {
          from: "src/assets/",
          to: "assets/",
        },
      ]

There are no asterisks (*) needed, and by default the folder assets will be created in dist.

As a (in this case unwanted) result of the build process, an empty main.js file will be produced in the dist folder. If this is not acceptable, it can be removed using the WebpackShellPluginNext plugin (needs to be installed and added to package.json), which simply deletes main.js at the end of the process.

const CopyPlugin = require("copy-webpack-plugin");
const fs = require("fs");
const WebpackShellPluginNext = require("webpack-shell-plugin-next");

const images = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/assets/",
          to: "assets/",
        },
      ],
    }),
    new WebpackShellPluginNext({
      onBuildEnd: {
        scripts: [
          () => {
            fs.unlinkSync("dist/main.js");
          },
        ],
      },
    }),
  ],
};

module.exports = [images];
Related