【问题标题】:copy files with copyWebpackPlugin使用 copyWebpackPlugin 复制文件
【发布时间】:2018-09-25 21:10:02
【问题描述】:

我正在使用 webpack 将文件从 /src/libs/** 复制到 /dist 目录,我的 copyWebpackPlugin 配置是

new copyWebpackPlugin([{
    from: __dirname + '/src/libs/**',
    to: __dirname + '/dist'
}])

但它会在 dist 中生成一个额外的 src 文件夹。我希望我的目标文件夹是 /dist/copy-files 但它是 /dist/src/copy-files。有什么解决方案吗?

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    对于遇到此问题但没有发现上述工作正常的任何谷歌同事,最终为我工作的是以下内容(在 Wordpress 项目中):

    // I have my development files in a "src" folder within the ./themes/THEMENAME folder
    // I have my output / live files in a "dist" folder in the ./themes/THEMENAME folder
    
    module.exports = {
        // ...other config
        output: {
            path: path.resolve(__dirname, "./wp-content/themes/THEMENAME/dist"),
            filename: "./js/[name].min.js"
        },
        plugins: [
            new CopyWebpackPlugin([{ 
                context: "./wp-content/themes/THEMENAME/src",
                from: "images/**/**"
                // I *did not* have to put a 'to' property here
            }])
        ]
    }
    

    以上配置允许我将所有图像文件从 ./src/images 复制到 ./dist/images。排序后,您可以使用例如ImageMinPlugin 压缩 dist 文件夹中的图像。

    【讨论】:

      【解决方案2】:

      您必须区分contextfrom

      • context 是源文件的根路径,不会添加到目标路径中。
      • from:但是,由from glob 确定的路径将被添加到目标路径中。

      所以在你的情况下,试试

      new copyWebpackPlugin([{
          context: __dirname + '/src',
          from: 'libs/**',
          to: __dirname + '/dist'
      }])
      

      改为。

      【讨论】:

        【解决方案3】:

        如果要复制多个文件夹,可以这样完成:

        .addPlugin(new CopyWebpackPlugin([
            // copies to {output}/static
            {
              from: './assets/adminlte', to: 'adminlte'
            }
        ]))
        
        .addPlugin(new CopyWebpackPlugin([
            // copies to {output}/static
            {
                from: './assets/radical', to: 'radical'
            }
        ]))
        

        这是我在symfony 4上的解决方案

        【讨论】:

          【解决方案4】:

          如果您在to 中使用绝对路径,则copy-webpack-plugin 会将解析后的from 添加到其中。
          要获得所需的内容,只需命名目录即可。

          new copyWebpackPlugin([{
              from: __dirname + '/src/libs/**',
              to: 'dist'
          }])
          

          from 路径也不需要是绝对的。它不会改变结果,但仍然可能更干净一些。

          new copyWebpackPlugin([{
              from: 'src/libs/**',
              to: 'dist'
          }])
          

          【讨论】:

            猜你喜欢
            • 2018-08-09
            • 2017-12-15
            • 2018-01-05
            • 1970-01-01
            • 2019-11-02
            • 2020-05-15
            • 2012-01-24
            • 2016-04-22
            • 2011-01-23
            相关资源
            最近更新 更多