CopyWebpackPlugin 的使用方法记录

CopyWebpackPlugin 一个webpack插件

  1. 用来复制一个单独的文件或者整个目录到新建的文件夹下

  2. 通常用在我们打包的时候,将一些文件放到指定的文件夹下

安装命令

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

先检查自己的版本吧(我就被坑了╮(╯▽╰)╭)不同版本的文档不一样

在这里插入图片描述我这里是6.0.4版本的

文档地址
https://webpack.js.org/plugins/copy-webpack-plugin/

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

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

我简单的示例

  new CopyWebpackPlugin(
      {
        patterns: [
          { from: 'F:\\canvas\\day02-canvas\\img\\clock.jpg' },
          // { from: 'other', to: 'public' },
        ],
      }),
  new CopyWebpackPlugin(
      {
        patterns: [
          { from: path.resolve(__dirname,'1.jpg') },
          // { from: 'other', to: 'public' },
        ],
      }),

4.xxx.xx版本的吧 做个记录

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

module.exports = {
    context: path.join(__dirname, 'app'),
    devServer: {
        // This is required for older versions of webpack-dev-server
        // if you use absolute 'to' paths. The path should be an
        // absolute path to your build destination.
        outputPath: path.join(__dirname, 'build')
    },
    plugins: [
        new CopyWebpackPlugin([
            // {output}/file.txt
            { from: 'from/file.txt' },

            // equivalent
            'from/file.txt',

            // {output}/to/file.txt
            { from: 'from/file.txt', to: 'to/file.txt' },

            // {output}/to/directory/file.txt
            { from: 'from/file.txt', to: 'to/directory' },

            // Copy directory contents to {output}/
            { from: 'from/directory' },

            // Copy directory contents to {output}/to/directory/
            { from: 'from/directory', to: 'to/directory' },

            // Copy glob results to /absolute/path/
            { from: 'from/directory/**/*', to: '/absolute/path' },

            // Copy glob results (with dot files) to /absolute/path/
            {
                from: {
                    glob:'from/directory/**/*',
                    dot: true
                },
                to: '/absolute/path'
            },

            // Copy glob results, relative to context
            {
                context: 'from/directory',
                from: '**/*',
                to: '/absolute/path'
            },

            // {output}/file/without/extension
            {
                from: 'path/to/file.txt',
                to: 'file/without/extension',
                toType: 'file'
            },

            // {output}/directory/with/extension.ext/file.txt
            {
                from: 'path/to/file.txt',
                to: 'directory/with/extension.ext',
                toType: 'dir'
            }
        ], {
            ignore: [
                // Doesn't copy any files with a txt extension    
                '*.txt',

                // Doesn't copy any file, even if they start with a dot
                '**/*',

                // Doesn't copy any file, except if they start with a dot
                { glob: '**/*', dot: false }
            ],

            // By default, we only copy modified files during
            // a watch or webpack-dev-server build. Setting this
            // to `true` copies all files.
            copyUnmodified: true
        })
    ]
};
<think> 我们正在处理关于copy-webpack-plugin v5.x版本的使用方法的问题。根据引用[2]中的信息,我们知道在Node.js版本过低时,使用该插件可能会出现问题,因此建议确保Node.js版本至少为14.17.6以上(但注意,v5.x可能对Node版本要求较低,不过为了兼容性,建议使用较新的Node版本)。 由于引用中并没有直接提供v5.x的具体配置方法,但我们可以根据copy-webpack-plugin的官方文档(v5.x)来总结使用步骤: ### 安装 首先,安装v5.x版本的copy-webpack-plugin: ```bash npm install copy-webpack-plugin@5 --save-dev ``` ### 基本配置 在webpack配置文件中(例如`webpack.config.js`)引入插件并配置: ```javascript const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { // ...其他配置 plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'source', to: 'dest' }, // 基本用法,将source目录下的文件复制到输出目录的dest子目录下 { from: 'other', to: 'public' } ] }) ] }; ``` ### 配置选项说明 在v5.x中,配置的核心是`patterns`数组,每个对象表示一个复制规则,常用属性: - `from`: 源文件或目录,可以是相对路径或绝对路径。 - `to`: 目标路径,相对于webpack的输出目录(output.path)。可以是字符串,也可以是函数(动态生成目标路径)。 - `context`: 可选,设置`from`的上下文,默认为当前webpack配置文件的上下文(context)。 - `globOptions`: 可选,传递给`glob`的选项,例如忽略文件: ```javascript { from: 'assets', to: 'assets', globOptions: { ignore: ['**/.*', '**/ignored.txt'] // 忽略所有点开头的文件和ignored.txt } } ``` - `filter`: 可选,过滤函数,返回true则复制,否则不复制。 ### 示例:忽略特定文件 参考引用[4](但注意我们这里使用的是v5.x的语法,实际上v5.x和v6.x在配置忽略上类似): ```javascript new CopyWebpackPlugin({ patterns: [ { from: path.resolve(__dirname, 'public'), to: '', globOptions: { ignore: ['**/index.html'] // 忽略public目录下的index.html } } ] }) ``` ### 注意事项 1. **Node版本**:如引用[2]所述,确保Node.js版本足够(>=10.0.0,但推荐>=12.0.0)。 2. **路径问题**:使用绝对路径可以避免路径错误的问题。可以使用`path.resolve(__dirname, 'path')`来获取绝对路径。 3. **版本差异**:v5.x与v6.x的主要区别在于v6.x修复了一些bug并增加了新的特性,但基础配置相似。如果你使用的是Webpack 4,v5.x是兼容的(Webpack 5建议使用v6.x以上)。 ### 完整示例 以下是一个在Webpack 4中使用copy-webpack-plugin v5.x的完整配置示例: ```javascript const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new CopyWebpackPlugin({ patterns: [ { from: path.resolve(__dirname, 'public/favicon.ico'), to: path.resolve(__dirname, 'dist') }, { from: path.resolve(__dirname, 'assets'), to: 'assets', globOptions: { ignore: ['**/*.txt'] // 忽略所有txt文件 } } ] }) ] }; ``` ### 相关问题 §§相关问题§§ 1. 如何在使用 copy-webpack-plugin v5.x 时忽略隐藏文件(如 .gitkeep)? 2. copy-webpack-plugin v5.x 和 v6.x 在配置上有哪些主要区别? 3. 在 Webpack 4 中使用 copy-webpack-plugin 时如何处理重复文件问题? </think> ### CopyWebpackPlugin v5.x 使用指南 #### 安装 v5.x 版本 ```bash npm install copy-webpack-plugin@5 --save-dev ``` 或指定精确版本(推荐): ```bash npm install copy-webpack-plugin@5.1.0 --save-dev ``` #### 基础配置(Webpack 4 环境) ```javascript const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { plugins: [ new CopyWebpackPlugin({ patterns: [ // 基础用法:复制文件 { from: 'src/assets', to: 'assets' }, // 复制单个文件 { from: 'src/favicon.ico', to: 'favicon.ico' }, // 使用通配符 { from: 'src/images/*.png', to: 'images/[name].[ext]' } ] }) ] } ``` #### 核心配置参数 1. **文件过滤**(忽略特定文件): ```javascript new CopyWebpackPlugin({ patterns: [{ from: 'public', to: 'public', globOptions: { ignore: [ '**/.DS_Store', // 忽略系统文件 '**/test-data/**', // 忽略测试目录 '**/*.tmp' // 忽略临时文件 ] } }] }) ``` 2. **路径转换**: ```javascript { from: 'src/static/**/*', to: ({ context, absoluteFilename }) => { return 'static/' + path.relative(context, absoluteFilename); } } ``` 3. **文件过滤函数**: ```javascript { from: 'docs', filter: (filePath) => { return filePath.endsWith('.pdf'); // 只复制PDF文件 } } ``` #### 常见问题解决 1. **Node 版本兼容问题**(参考引用[2]): - 确保 Node.js ≥ 14.17.6(老版本需升级) - 错误示例:`HookWebpackError: Not supported` 2. **路径错误处理**: ```javascript // 使用绝对路径避免问题 const path = require('path'); { from: path.resolve(__dirname, 'src/assets'), to: path.resolve(__dirname, 'dist/assets') } ``` 3. **复制后文件修改**: ```javascript { from: 'config.json', to: 'config.prod.json', transform: (content) => { return content.toString().replace('DEBUG=true', 'DEBUG=false'); } } ``` #### 完整示例 ```javascript const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new CopyWebpackPlugin({ patterns: [ { from: path.resolve(__dirname, 'public'), to: 'public', globOptions: { ignore: ['**/temp/**', '**/*.log'] } }, { from: 'src/manifest.json', to: 'manifest.json', transform: (content) => { const manifest = JSON.parse(content); manifest.version = process.env.VERSION; return JSON.stringify(manifest, null, 2); } } ] }) ] }; ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值