Giter Site home page Giter Site logo

copy-webpack-plugin's Introduction

npm node tests cover discussion size

copy-webpack-plugin

Copies individual files or entire directories, which already exist, to the build directory.

Getting Started

To begin, you'll need to install copy-webpack-plugin:

npm install copy-webpack-plugin --save-dev

or

yarn add -D copy-webpack-plugin

or

pnpm add -D copy-webpack-plugin

Then add the plugin to your webpack config. For example:

webpack.config.js

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

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "source", to: "dest" },
        { from: "other", to: "public" },
      ],
    }),
  ],
};

Note

copy-webpack-plugin is not designed to copy files generated from the build process; rather, it is to copy files that already exist in the source tree, as part of the build process.

Note

If you want webpack-dev-server to write files to the output directory during development, you can force it with the writeToDisk option or the write-file-webpack-plugin.

Note

You can get the original source filename from Asset Objects.

Options

The plugin's signature:

webpack.config.js

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

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "source", to: "dest" },
        "path/to/source", // absolute or relative, files/directories/globs - see below for examples
      ],
      options: {
        concurrency: 100,
      },
    }),
  ],
};

Patterns

from

Type:

type from = string;

Default: undefined

Glob or path from where we copy files. Globs accept fast-glob pattern-syntax. Glob can only be a string.

Warning

Don't use directly \\ in from option if it is a glob (i.e path\to\file.ext) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator. On Windows, the forward slash and the backward slash are both separators. Instead please use /.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        "relative/path/to/file.ext",
        "relative/path/to/dir",
        path.resolve(__dirname, "src", "file.ext"),
        path.resolve(__dirname, "src", "dir"),
        "**/*",
        {
          from: "**/*",
        },
        // If absolute path is a `glob` we replace backslashes with forward slashes, because only forward slashes can be used in the `glob`
        path.posix.join(
          path.resolve(__dirname, "src").replace(/\\/g, "/"),
          "*.txt",
        ),
      ],
    }),
  ],
};
For windows

If you define from as absolute file path or absolute folder path on Windows, you can use windows path segment (\\)

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "file.txt"),
        },
      ],
    }),
  ],
};

But you should always use forward-slashes in glob expressions See fast-glob manual.

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          // If absolute path is a `glob` we replace backslashes with forward slashes, because only forward slashes can be used in the `glob`
          from: path.posix.join(
            path.resolve(__dirname, "fixtures").replace(/\\/g, "/"),
            "*.txt",
          ),
        },
      ],
    }),
  ],
};

The context behaves differently depending on what the from is (glob, file or dir). More examples

to

Type:

type to =
  | string
  | ((pathData: { context: string; absoluteFilename?: string }) => string);

Default: compiler.options.output

string

Output path.

Warning

Don't use directly \\ in to (i.e path\to\dest) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator. On Windows, the forward slash and the backward slash are both separators. Instead please use / or path methods.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "**/*",
          to: "relative/path/to/dest/",
        },
        {
          from: "**/*",
          to: "/absolute/path/to/dest/",
        },
        {
          from: "**/*",
          to: "[path][name].[contenthash][ext]",
        },
      ],
    }),
  ],
};
function

Allows to modify the writing path.

Warning

Don't return directly \\ in to (i.e path\to\newFile) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator. On Windows, the forward slash and the backward slash are both separators. Instead please use / or path methods.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to({ context, absoluteFilename }) {
            return "dest/newPath/[name][ext]";
          },
        },
      ],
    }),
  ],
};

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to({ context, absoluteFilename }) {
            return Promise.resolve("dest/newPath/[name][ext]");
          },
        },
      ],
    }),
  ],
};

context

Type:

type context = string;

Default: options.context|compiler.options.context

A path to be (1) prepended to from and (2) removed from the start of the result path(s).

Warning

Don't use directly \\ in context (i.e path\to\context) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator. On Windows, the forward slash and the backward slash are both separators. Instead please use / or path methods.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.txt",
          to: "dest/",
          context: "app/",
        },
      ],
    }),
  ],
};

context can be an absolute path or a relative path. If it is a relative path, then it will be converted to an absolute path based on compiler.options.context.

context should be explicitly set only when from contains a glob. Otherwise, context is automatically set, based on whether from is a file or a directory:

If from is a file, then context is its directory. The result path will be the filename alone.

If from is a directory, then context equals from. The result paths will be the paths of the directory's contents (including nested contents), relative to the directory.

The use of context is illustrated by these examples.

globOptions

Type:

type globOptions = import("globby").Options;

Default: undefined

Allows to configure the glob pattern matching library used by the plugin. See the list of supported options To exclude files from the selection, you should use globOptions.ignore option

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "public/**/*",
          globOptions: {
            dot: true,
            gitignore: true,
            ignore: ["**/file.*", "**/ignored-directory/**"],
          },
        },
      ],
    }),
  ],
};

filter

Type:

type filter = (filepath: string) => boolean;

Default: undefined

Note

To ignore files by path please use the globOptions.ignore option.

webpack.config.js

const fs = require("fs").promise;

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "public/**/*",
          filter: async (resourcePath) => {
            const data = await fs.promises.readFile(resourcePath);
            const content = data.toString();

            if (content === "my-custom-content") {
              return false;
            }

            return true;
          },
        },
      ],
    }),
  ],
};

toType

Type:

type toType = "dir" | "file" | "template";

Default: undefined

Determinate what is to option - directory, file or template. Sometimes it is hard to say what is to, example path/to/dir-with.ext. If you want to copy files in directory you need use dir option. We try to automatically determine the type so you most likely do not need this option.

Name Type Default Description
'dir' string undefined If to has no extension or ends on '/'
'file' string undefined If to is not a directory and is not a template
'template' string undefined If to contains a template pattern
'dir'

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "path/to/file.txt",
          to: "directory/with/extension.ext",
          toType: "dir",
        },
      ],
    }),
  ],
};
'file'

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "path/to/file.txt",
          to: "file/without/extension",
          toType: "file",
        },
      ],
    }),
  ],
};
'template'

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/",
          to: "dest/[name].[contenthash][ext]",
          toType: "template",
        },
      ],
    }),
  ],
};

force

Type:

type force = boolean;

Default: false

Overwrites files already in compilation.assets (usually added by other plugins/loaders).

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/**/*",
          to: "dest/",
          force: true,
        },
      ],
    }),
  ],
};

priority

Type:

type priority = number;

Default: 0

Allows to specify the priority of copying files with the same destination name. Files for patterns with higher priority will be copied later. To overwrite files, the force option must be enabled.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        // Copied second and will overwrite "dir_2/file.txt"
        {
          from: "dir_1/file.txt",
          to: "newfile.txt",
          force: true,
          priority: 10,
        },
        // Copied first
        {
          from: "dir_2/file.txt",
          to: "newfile.txt",
          priority: 5,
        },
      ],
    }),
  ],
};

transform

Type:

type transform =
  | {
      transformer: (input: string, absoluteFilename: string) => string | Buffer;
      cache?: boolean | TransformerCacheObject | undefined;
    }
  | ((input: string, absoluteFilename: string) => string | Buffer);

Default: undefined

Allows to modify the file contents.

function

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          // The `content` argument is a [`Buffer`](https://nodejs.org/api/buffer.html) object, it could be converted to a `String` to be processed using `content.toString()`
          // The `absoluteFrom` argument is a `String`, it is absolute path from where the file is being copied
          transform(content, absoluteFrom) {
            return optimize(content);
          },
        },
      ],
    }),
  ],
};
object
Name Default Description
transformer undefined Allows to modify the file contents.
cache false Enable transform caching. You can use transform: { cache: { key: 'my-cache-key' } } to invalidate the cache.
transformer

Type:

type transformer = (input: string, absoluteFilename: string) => string;

Default: undefined

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          // The `content` argument is a [`Buffer`](https://nodejs.org/api/buffer.html) object, it could be converted to a `String` to be processed using `content.toString()`
          // The `absoluteFrom` argument is a `String`, it is absolute path from where the file is being copied
          transform: {
            transformer(content, absoluteFrom) {
              return optimize(content);
            },
          },
        },
      ],
    }),
  ],
};

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          transform: {
            transformer(content, path) {
              return Promise.resolve(optimize(content));
            },
          },
        },
      ],
    }),
  ],
};
cache

Type:

type cache =
  | boolean
  | {
      keys: {
        [key: string]: any;
      };
    }
  | {
      keys: (
        defaultCacheKeys: {
          [key: string]: any;
        },
        absoluteFilename: string,
      ) => Promise<{
        [key: string]: any;
      }>;
    }
  | undefined;

Default: false

webpack.config.js

Enable/disable and configure caching. Default path to cache directory: node_modules/.cache/copy-webpack-plugin.

boolean

Enables/Disable transform caching.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          transform: {
            transformer(content, path) {
              return optimize(content);
            },
            cache: true,
          },
        },
      ],
    }),
  ],
};
object

Enables transform caching and setup invalidation keys.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          transform: {
            transformer(content, path) {
              return optimize(content);
            },
            cache: {
              keys: {
                // May be useful for invalidating cache based on external values
                // For example, you can invalid cache based on `process.version` - { node: process.version }
                key: "value",
              },
            },
          },
        },
      ],
    }),
  ],
};

You can setup invalidation keys using a function.

Simple function:

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          transform: {
            transformer(content, path) {
              return optimize(content);
            },
            cache: {
              keys: (defaultCacheKeys, absoluteFrom) => {
                const keys = getCustomCacheInvalidationKeysSync();

                return {
                  ...defaultCacheKeys,
                  keys,
                };
              },
            },
          },
        },
      ],
    }),
  ],
};

Async function:

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/*.png",
          to: "dest/",
          transform: {
            transformer(content, path) {
              return optimize(content);
            },
            cache: {
              keys: async (defaultCacheKeys, absoluteFrom) => {
                const keys = await getCustomCacheInvalidationKeysAsync();

                return {
                  ...defaultCacheKeys,
                  keys,
                };
              },
            },
          },
        },
      ],
    }),
  ],
};

transformAll

Type:

type transformAll = (
  data: {
    data: Buffer;
    sourceFilename: string;
    absoluteFilename: string;
  }[],
) => any;

Default: undefined

Allows you to modify the contents of multiple files and save the result to one file.

Note

The to option must be specified and point to a file. It is allowed to use only [contenthash] and [fullhash] template strings.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/**/*.txt",
          to: "dest/file.txt",
          // The `assets` argument is an assets array for the pattern.from ("src/**/*.txt")
          transformAll(assets) {
            const result = assets.reduce((accumulator, asset) => {
              // The asset content can be obtained from `asset.source` using `source` method.
              // The asset content is a [`Buffer`](https://nodejs.org/api/buffer.html) object, it could be converted to a `String` to be processed using `content.toString()`
              const content = asset.data;

              accumulator = `${accumulator}${content}\n`;
              return accumulator;
            }, "");

            return result;
          },
        },
      ],
    }),
  ],
};

noErrorOnMissing

Type:

type noErrorOnMissing = boolean;

Default: false

Doesn't generate an error on missing file(s).

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "missing-file.txt"),
          noErrorOnMissing: true,
        },
      ],
    }),
  ],
};

info

Type:

type info =
  | Record<string, any>
  | ((item: {
      absoluteFilename: string;
      sourceFilename: string;
      filename: string;
      toType: ToType;
    }) => Record<string, any>);

Default: undefined

Allows to add assets info.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        "relative/path/to/file.ext",
        {
          from: "**/*",
          // Terser skip this file for minimization
          info: { minimized: true },
        },
      ],
    }),
  ],
};

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        "relative/path/to/file.ext",
        {
          from: "**/*",
          // Terser skip this file for minimization
          info: (file) => ({ minimized: true }),
        },
      ],
    }),
  ],
};

Options

concurrency

type:

type concurrency = number;

default: 100

limits the number of simultaneous requests to fs

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [...patterns],
      options: { concurrency: 50 },
    }),
  ],
};

Examples

Different variants of from (glob, file or dir).

Take for example the following file structure:

src/directory-nested/deep-nested/deepnested-file.txt
src/directory-nested/nested-file.txt
From is a Glob

Everything that you specify in from will be included in the result:

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/directory-nested/**/*",
        },
      ],
    }),
  ],
};

Result:

src/directory-nested/deep-nested/deepnested-file.txt,
src/directory-nested/nested-file.txt

If you don't want the result paths to start with src/directory-nested/, then you should move src/directory-nested/ to context, such that only the glob pattern **/* remains in from:

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "**/*",
          context: path.resolve(__dirname, "src", "directory-nested"),
        },
      ],
    }),
  ],
};

Result:

deep-nested/deepnested-file.txt,
nested-file.txt
From is a Dir

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "src", "directory-nested"),
        },
      ],
    }),
  ],
};

Result:

deep-nested/deepnested-file.txt,
nested-file.txt

Technically, this is **/* with a predefined context equal to the specified directory.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "**/*",
          context: path.resolve(__dirname, "src", "directory-nested"),
        },
      ],
    }),
  ],
};

Result:

deep-nested/deepnested-file.txt,
nested-file.txt
From is a File
module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(
            __dirname,
            "src",
            "directory-nested",
            "nested-file.txt",
          ),
        },
      ],
    }),
  ],
};

Result:

nested-file.txt

Technically, this is a filename with a predefined context equal to path.dirname(pathToFile).

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "nested-file.txt",
          context: path.resolve(__dirname, "src", "directory-nested"),
        },
      ],
    }),
  ],
};

Result:

nested-file.txt

Ignoring files

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.posix.join(
            path.resolve(__dirname, "src").replace(/\\/g, "/"),
            "**/*",
          ),
          globOptions: {
            ignore: [
              // Ignore all `txt` files
              "**/*.txt",
              // Ignore all files in all subdirectories
              "**/subdir/**",
            ],
          },
        },
      ],
    }),
  ],
};

Flatten copy

Removes all directory references and only copies file names.

Warning

If files have the same name, the result is non-deterministic.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: "src/**/*",
          to: "[name][ext]",
        },
      ],
    }),
  ],
};

Result:

file-1.txt
file-2.txt
nested-file.txt

Copy in new directory

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          // When copying files starting with a dot, must specify the toType option
          // toType: "file",
          to({ context, absoluteFilename }) {
            return `newdirectory/${path.relative(context, absoluteFilename)}`;
          },
          from: "directory",
        },
      ],
    }),
  ],
};

Result:

"newdirectory/file-1.txt",
"newdirectory/nestedfile.txt",
"newdirectory/nested/deep-nested/deepnested.txt",
"newdirectory/nested/nestedfile.txt",

Skip running JavaScript files through a minimizer

Useful if you need to simply copy *.js files to destination "as is" without evaluating and minimizing them using Terser.

webpack.config.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        "relative/path/to/file.ext",
        {
          from: "**/*",
          // Terser skip this file for minimization
          info: { minimized: true },
        },
      ],
    }),
  ],
};
yarn workspaces and monorepos

When using yarn workspaces or monorepos, relative copy paths from node_modules can be broken due to the way packages are hoisting. To avoid this, should explicitly specify where to copy the files from using require.resolve.

webpack.config.js

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

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

copy-webpack-plugin's People

Contributors

akx avatar alan-agius4 avatar alexander-akait avatar anshumanv avatar ariasuni avatar cap-bernardito avatar cletusw avatar clydin avatar dependabot[bot] avatar ersachin3112 avatar evilebottnawi avatar fetz avatar gajus avatar gribnoysup avatar joshwiens avatar kevlened avatar klu235 avatar mderazon avatar mgcrea avatar mhxbe avatar michael-ciniawsky avatar mikesherov avatar mlegenhausen avatar munter avatar patrickjs avatar ream88 avatar scottdotjs avatar slavafomin avatar snitin315 avatar tommytroylin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

copy-webpack-plugin's Issues

Copied file is empty

I'm trying to copy the output file of Webpack into another folder and I'm getting this random error where sometimes the copied file is empty.

image

The original file is not empty.

image

I'm doing this to copy the file:

            new CopyWebpackPlugin([
                  {
                        from: "./build/build.js",
                        to: "../../FRONT/js/build.js"
                  }
            ])

It's the first time I'm using Webpack...

Could this be a bug or am I doing something wrong?

copying using glob unexpected behaviour

Hi,

Assume I have the following dir structure

- src
-- app
--- picture.png
--- subdir
----- subpicture.png
--- stuff.txt
-- assets
--- stuff.txt

When I do a copy, in a new context of dist, using

new CopyWebpackPlugin([
      {
        from: 'src/assets',
        to: 'assets'
      }
])

it will copy all the files from src/assets to dist/assets.
But when I do a copy, in the same context of dist, using:

    new CopyWebpackPlugin([
      {
        from: 'src/assets',
        to: 'assets'
      },
      {
        from: 'src/app/**/*.png',
        to: 'app'
      }
    ])

it will copy all the files from src/assets to dist/assets but copy the png files in src/app to dist/src/**/**.png. ( mind the 'src' )

This is very confusing behaviour, which I feel is not expected. So what's up? :)

Kind regards
Sam V.

Add debug information printed in WebPack debug mode

Currently plugin doesn't copy anything for me so I would like debugging mode to be available. I'm using the following config:

var CopyWebpackPlugin = require ( 'copy-webpack-plugin' );

module.exports = {
    debug: true,
    externals: { jquery: "jQuery" },

    entry: './res/js/entry.ts',
    output: {
        path: __dirname + "/web",
        filename: 'js/app.js'
    },
    module: {
        loaders: [
            // note that babel-loader is not required
            { test: /\.tsx?$/, loader: 'ts-loader' }
        ],
        plugins: [
            new CopyWebpackPlugin ( [
                    // {output}/file.txt
                    {
                        from: __dirname + '/node_modules/bootstrap/dist/bootstrap.min.js',
                        to: "js"
                    }
                ]
            )
        ]
    }
};

Copy files from a directory to a different directory

I want to copy files of a given file from one directory to a different directory in the result.

What I have now is

new CopyWebpackPlugin([{
    from: `${__dirname}/app/images/homescreens/*.png`, to: `homescreens/` }
}])

I want the files, that are in app/images/homescreens, to be in dist/homescreens/ where dist/ is the output directory. However, whenever I use globs like that, the to is ignored and the files are copied into dist/app/images/homescreens/. What should I do?

is there a debug mod?

is there a debug mode to be able to see what files are copied.
because I added the right configuration but nothing copied and my service started without any problem. But I have missing files in my public folder.

not copy the files in node v 6.0.0

This is my plugin configuration:

new CopyWebpackPlugin([
   { from: 'src/image', to: 'image' },
   { from: 'src/vendor', to: 'vendor' }
])

It works fine with node v 5.8.1 but it does not copy any file with node v 6.0.0.

Webpack shows 'ERROR in Path must be a string. Received undefined' in the console.

permission denied, mkdir

After upgrading from version 1.1.1 to 2.0.0 I get the following error... no other configuration has changed.

Unhandled rejection Error: EACCES: permission denied, mkdir '/_karma_webpack_'
    at Error (native)

Is this a known issue? Do you have any idea what might be going on? I looked around but couldn't find anything.
Downgrading back to 1.1.1 works as before, which is pretty weird given the error is related to permission denied.

Doesn't Work Node 6.1

It doesn't appear to be working for Node 6.1. I am getting this error:

ERROR in EISDIR: illegal operation on a directory, read

Absolute paths don’t work

{
    from: '/Users/rauschma/react-test/html',
    to: '/Users/rauschma/react-test/build'
}

These two paths lead to:

  • /Users/rauschma/react-test/html/index.html being copied to
  • /Users/rauschma/react-test/build/Users/rauschma/react-test/build/index.html

Throw error if source or target does not exist

Plugin doesn't copy anything anywhere for me and I guess I made a mistake in paths. I guess this should be an error in the plugin when from orto is not recognized as a correct, accessible file or directory.

It doesn't work with webpack-dev-server

I have nearly the same config for building and for watching, but when using watch, no output folder gets created and no error is shown in the console.

new CopyWebpackPlugin([{ from: path.join(__dirname, '../resources')}], { copyUnmodified: true }),
devServer: {
    hot: true,
    port: 8080,
    host: '0.0.0.0',
    inline: true,
    contentBase: path.join(__dirname, '../www'),
    outputPath: path.join(__dirname, '../www'),
    publicPath: '/',
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  }

No option to match dots

Minimatch's options param is not exposed, so right now copy-webpack can't ignore files like '.eslint' using a pattern like '**/*'

function shouldIgnore(pathName, ignoreList) {
  var matched = _.find(ignoreList, function(glob) {
    return minimatch(pathName, glob, {
      matchBase: true,
      dot: true
    });
  });

Absolute paths don't work on Windows

On 1.1.1

Config:

    new CopyWebpackPlugin([
        {from: 'src/assets/*.*', to: path.resolve(__dirname, '../dist')}
    ])

I had to revert to 1.0.0 to get this working

The path resolves to C:\node\sp_app\dist

Possible to run on file change/addition/deletion when using webpack watch?

When running webpack watch is it possible to have the files copied over automatically when a change happens? For example, if a new image is added to the folder automatically copy it over to the destination folder, or delete an image if it is deleted from the from folder or change the file name if it changes ect... Currently, you have to restart webpack --watch or run the build again for the changes to take into effect.

[Feature] Support `context` globs

I have a series of react components in folders that all have their own images folder. I'd really like to be able to glob the context and then copy the images and folders inside that context to a destination.

Is this ^^ possible? I've tried the following, but it doesn't seem to work:

new CopyWebpackPlugin([
  {
    context: `${__dirname}/src/**/images`,
    from: '**/*',
    to: path.join(__dirname, '.temp/static/images/')
  }
]),

And doing:

new CopyWebpackPlugin([
  {
    context: `${__dirname}/src/`,
    from: '**/images/**/*',
    to: path.join(__dirname, '.temp/static/images/')
  }
]),

Has the annoying consequence of copying all the parent folders to images.

e.g: .temp/static/images/components/posts/images/2x/header.png

I could use flatten: true to remove the parent folders, but that would also remove the child folders inside of the component images folder, and i want to preserve them :(

Do not use fs to copy files; declare target files as assets to webpack

The current implementation is doing the heavy lifting of creating directory structure and copying the files. A better approach would be to simply add the target files to the webpack assets collection (e.g. html-webpack-plugin ./lib/compiler.js does just that). Leave it up to webpack to copy the assets.

With this setup, for those who want copy-webpack-plugin to work with webpack-dev-server you can use write-file-webpack-plugin.

2.1.4 broke something

Using AngularClass/angular2-webpack-starter with 2.1.4 (with node 5.10.1) raises an error

new CopyWebpackPlugin([{from: 'src/assets', to: 'assets'}]),
TypeError: CopyWebpackPlugin is not a function

reverting to 2.1.3 is OK. Something changed in your build process that makes the package fails with my setup. I'm on hurry, so i cannot investigate more for now, sorry.

[Bug] `after-emit` callbacks are called multiple times in watch mode

I noticed that when defining after-emit,

compiler.plugin("after-emit", function(compilation, cb) {

it makes the emit run multiple times when webpack is in watch mode. To see this we can write a console.log statement in emit:

  compiler.plugin('emit', function(compilation, cb) {
    console.log("emit...");

After running webpack -watch we get

emit...
emit...
emit...
emit...

If we comment out the after-emit block then webpack only calls emit when we modify one of our project files. Now correct me if I'm wrong, but the after emit section is just to add the files that we are copying as dependencies, and so webpack is watching for changes in these files. This is fine I guess, but if we are only copying the bundled files somewhere else then watching over these files seems like a waste of time, especially if we know that they haven't changed.

Perhaps we could check if the file is being already tracked by webpack:

  var currentAssets = _.keys(compilation.assets);
  var inProduction = _.find(currentAssets, function(name) {
    return _.endsWith(absFileSrc, name);
  });

and only add the file to fileDependencies if inProduction is undefined:

if (!inProduction) {
  fileDependencies.push(absFileSrc);
}

The problem with be with the contextDependencies though.

Globs for `from`

Would be much easier to follow than inverted exclude patterns.

"Error: EMFILE: too many open files, open.." on Windows

That's pretty much the issue.
Works fine on OS X

Have googled and can't find any way to increase Windows open file limit.
Is now also happening on OS X 'ENFILE: file table overflow'

As far as I can tell this module always works down to an individual file level in async.

I've worked around this by changing the app structure (it will be the ~8000 files in node_modules) and doing a shell cp instead.

Is it something you need to look at handling via something like graceful-fs?

Add linting rules

There are no linting rules making it hard to enforce a consistent code style of the PRs.

Plugin should fail when file not found

Would you accept a PR to fail the build when the from file or directory is not found?

Here's what happened this morning. Netlify allows static routing, but I need to copy _redirects into the output folder.

  new CopyWebpackPlugin([
    {
      from: path.join(__dirname, "/src/_redirects"),
      to: "_redirects",
      toType: "file"
    },
  ]),

Let's say someone (me, last night) changes the from field to:

from: path.resolve(__dirname, "/src/_redirects")

Now the file is not found (it's an absolute path) and is not copied to the output folder. Every page on the website besides the root path 404's. That shouldn't happen, the build should have failed instead.

Plugin failing

I have the following webpack.config file:

var webpack = require('webpack')
//copy files
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');

if(process.env.NODE_ENV === 'development'){
  var loaders = ['react-hot','babel']
} else {
  var loaders = ['babel']
}
module.exports = {
  devtool: 'eval',
  entry: './app-client.js',
  output: {
    path: __dirname + '/public/dist',
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: loaders,
      exclude: /node_modules/
    },
    { 
     test: /\.scss$/, 
     loaders: ["style", "css", "sass"] 
    }
  ]},
  plugins: [
    new webpack.DefinePlugin({
      'process.env.COSMIC_BUCKET': JSON.stringify(process.env.COSMIC_BUCKET)
    }),
    new CopyWebpackPlugin([
      { from: '/images/', to: '/public/img/' }
    ])
 ]
};

But for some reason the script is failing:

npm ERR! Darwin 13.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "webpack-dev-server"
npm ERR! node v5.8.0
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] webpack-dev-server: `NODE_ENV=development PORT=8080 webpack-dev-server --content-base public/ --hot --inline --devtool inline-source-map --history-api-fallback`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] webpack-dev-server script 'NODE_ENV=development PORT=8080 webpack-dev-server --content-base public/ --hot --inline --devtool inline-source-map --history-api-fallback'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the global-gamesey package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     NODE_ENV=development PORT=8080 webpack-dev-server --content-base public/ --hot --inline --devtool inline-source-map --history-api-fallback
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs global-gamesey
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls global-gamesey
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/travis.tb/git/global-gamesey/npm-debug.log

npm ERR! Darwin 13.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "development"
npm ERR! node v5.8.0
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] development: `cp views/index.html public/index.html && NODE_ENV=development webpack && npm run webpack-dev-server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] development script 'cp views/index.html public/index.html && NODE_ENV=development webpack && npm run webpack-dev-server'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the global-gamesey package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cp views/index.html public/index.html && NODE_ENV=development webpack && npm run webpack-dev-server
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs global-gamesey
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls global-gamesey
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/travis.tb/git/global-gamesey/npm-debug.log

All I want is to copy the files from my images directory into public/img at npm run development but I am not getting how webpack is handling this with this plugin.

ignoring toType: 'dir'

Hi
I might be doing it wrong, and any help would be greatly appreciated,
I'm copy files and trying to get them to appear in a certain directory but it seems to be ignoring what I set,
This is my webpack config:

var nodeModules = path.resolve(__dirname, '../node_modules');
new CopyWebpackPlugin([{
  from: nodeModules + '/angular-i18n/angular-locale*.js',
  to: 'angular/i18n',
  toType: 'dir'
}])

I want all the translation files to be in dist/angular/i18n/
but they appear in dist/node_modules/angular-i18n/

I realise I am setting the from to a file with an extension, but thought the toType would override this,
am I wrong?

The following does work, but copies all the files

var nodeModules = path.resolve(__dirname, '../node_modules');
new CopyWebpackPlugin([{
  from: nodeModules + '/angular-i18n',
  to: 'angular/i18n',
  toType: 'dir'
}])

copy dot files

I've this config:

new CopyWebpackPlugin([
        { from: `${paths.static}/pom.xml` },
        { from: `${paths.static}/.htaccess` }
      ], {
        ignore: []
      }),

however the file .htaccess isn't copied, what could be?

watch file not working in watch mode

As readme says:

By default, we only copy modified files during a watch or webpack-dev-server build.

But it's not working in my project. Here is the webpack.config.js

var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');

module.exports = {
    watch: true,
    entry: './deal/static/js/index.js',
    output: {
        path: './dist',
        filename: 'build.js'
    },
    plugins: [

        new CopyWebpackPlugin([
            {
                from: 'deal/page/index.html',
                to: 'index.html'
            }
        ])
    ]
};

PS: the index.html copied to the dist directory successfully, but can not watch the index.html.
Any suggestion will be helpful.

Add support for filename patterns

Please add support for filename patterns. I'd like to copy file to [name][hash].[ext]. Plugin should add the file to the webpack stats so that it would be possible to generate filename mapping file.

Does not copy files to actual output folder when webpack-dev-server is used

It appears that nothing happens when trying to copy some extra files (not bundled) to the output folder, under the webpack-dev-server logic:

devServer: {
            contentBase: './public',
            outputPath: path.resolve(ROOT_PATH, 'public'),
            historyApiFallback: true,
            hot: true,
            inline: true,
            port: 33000,
            progress: true
        },
        plugins: [
            new CopyWebpackPlugin([
                {from: 'src/css', to: 'css', force: true},
                {from: 'src/img', to: 'img', force: true}
            ]),
            new webpack.HotModuleReplacementPlugin(),
            new OpenBrowserPlugin({url: 'http://localhost:33000'})
        ]

Can this be done somehow? The webpack-dev-server needs this to show some external CSS and IMAGE files. I used to be doing this with gulp but now I want to get rid of this dependency.

Using your plugin with the simple webpack (for build) works perfectly but not for webpack-dev-server.

NOTE: I can achieve what I want if I use both webpack and webpack-dev-server on the start script, but this is not too elegant and done only for solving this problem:

  "scripts": {
    "build": "webpack",
    "start": "npm run build && webpack-dev-server"
  },

[Feature] keeping original whole or partial stats

We have cordova hooks in our source folder (see the cordova hooks guide for more info: https://cordova.apache.org/docs/en/dev/guide/appdev/hooks/) that need to be copied into our destination folder and need to preserve the executable bit on their file mode (i.e. ls -l should print -rwxr-xr-x for these files).

Currently this doesn't happen, but it seems like it should be easy to do by passing a options object as a 3rd parameter to the to the fs.writeFileAsync() call in the writeFilePromises with the stat.mode from the fs.statAsync() call.

Support for alias

in webpack config there is alias thing which im using when requiring the files.

 resolve: {
        modulesDirectories: [node, bower],
        alias: {
            'node': node,
            'bower': './bower-components'
        }
    },

and using that as require('bower/jquery/dist/jquery.min.js') . I want this to support for this plugin also.

Uglify output

I'm using copy-webpack-plugin to copy a file into a public directory, and I'm hoping to have it minified in the process (during production builds).

I'm using webpack.optimize.UglifyJsPlugin, but that only operates on the output of chunks, and the assets of copy-webpack-plugin don't belong to chunks so they aren't minified.

Do you know of a way to get Webpack to minify Javascript files copied using this plugin?

Error: CopyWebpackPlugin is not a function

I'm getting the following error when using Version 2.1.4:

module.exports = new CopyWebpackPlugin([{
^

TypeError: CopyWebpackPlugin is not a function
at Object. (build/copy.js:3:18)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object. (build/webpack.config.js:32:5)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at module.exports

2.1.3 runs without problems.

not working, no error, no files were copy

my folder structure

project
  |app
  |image

my config

module.exports = {
    context: __dirname + "/app",
    entry:[
        "./index.js"
    ],
    output: {
        path: __dirname + '/public',
        filename: "bundle.js",
        publicPath: "/public/"
    },
    plugins: [
        new CopyWebpackPlugin([{from: 'image'}])
    ]
}

ERROR in undefined is not a function

I am trying to copy an assets folder to my build directory. When I am running any type of webpack build commands I get an ERROR in undefined is not a function. It is working the way I am expecting it, but it does give me that message. I am one of those people that don't like error messages, so I was wondering if there was something I am not seeing here. I have all of the basic requirements to do the copy. Here is a rough look at my config file:

var info = require('./package.json');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {

    entry: {
        'polyfills': 'angular2/bundles/angular2-polyfills',
        'vendor': './src/vendor.ts',
        'app': './src/bootstrap.ts'
    },
    output: {
        path: path.join(__dirname, 'build/'),
        filename: 'bundle-' + info.name + '-[name]-' + info.version + '.js' 

    },
    devServer: {
        outputPath: path.join(__dirname, 'build')

    },
    context: path.join(__dirname),
    devtool: 'inline-source-map',
    resolve: {
        extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js', 
        '.tpl.html'],
        root: path.resolve('.src'),
        moduleDirectories: ['node_modules', 'src', 'typings']

    },
    module: {
        loaders: [
            {
                test: /\.ts(x?)$/,
                loader:'ts-loader',
                exclude: /node_modules/
            }
        ]

    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),
        new CopyWebpackPlugin([
            {
                from: 'src/assets',
                to: 'assets'

            }
        ])
    ]
};

I hope its just a stupid configuration issue, but I am lost at the moment.

Hardcoded path separator

if (_.first(relFileDest) === '/') {
      relFileDest = relFileDest.substr(1);
    }

Is the slash required by webpack? If it isn’t, I’d use path.sep, so that the plugin also works on Windows. Also: slice() is normally a better choice than substr() (which is not part of main ES5).

An exception on /**/* path with nested folders

When using path like assets/ * * / * to copy a number of files in nested folders, an exception is occured:
A global exception occured: { [Error: EINVAL: invalid argument, read] errno: -4071, code: 'EINVAL', syscall: 'read' }
A number of messages with exception match total number of nested folders, so seems like folders are causing it.
But files and folders are still copied successfully, if to handle global exceptions manually.

Replacing path with assets/ * * / * . * fixes issue. But probably this workaround would't work for files without extension.

ignore is not working

I am trying to move all files from my current folder to dist folder. node_modules is also present in current folder. I was trying to ignore node_modules folder whiile copying. I have used the following snippet:
new CopyWebpackPlugin( [ { from: '.' } ], { ignore: [ 'node_modules' ] } )

And this is not at all working

[Feature] copy files after webpack has finished creating the bundles

I was hoping that I could use this plugin to create copies of the generated bundles to other directories. It seems however that the copying starts while webpack is creating these bundles. As a result I end up with copies of the files with no content.

Is there a way to add an option so that the copying of the files happen after webpack has created the output files?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.