代码之家  ›  专栏  ›  技术社区  ›  user687554

Webpack-使用CopyWebpackPlugin将文件从源复制到公共

  •  21
  • user687554  · 技术社区  · 7 年前

    我有一个应用程序,我在其中使用网页包。在这个应用程序中,我需要从我的 source 目录中的相同层次结构 public 目录为了做到这一点,我使用了 CopyWebpackPlugin 。此时,我的webpack.config。js文件如下所示:

    const path = require('path');
    const projectRoot = path.resolve(__dirname, '../');
    
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    
    module.exports = {
      entry: {
        app: './source/index.html.js',
      },
      output: {
        path: path.resolve(__dirname, 'public'),
        filename: '[name].package.js'
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            loaders: ['style-loader','css-loader']        
          },
        ]
      },
      plugins: [
        new CopyWebpackPlugin(
          [ { from: './source/**/*.html', to: './public', force:true } ],
          { copyUnmodified: true }
        )
      ]
    };
    

    当我跑步时 webpack 目录但是,复制时,会包含源目录名。例如,如果我的目录结构如下:

    /source
      /dir-1
        /child-a
          index.html
          page.html
        /child-b
          index.html
          contact.html
      /dir-2
        index.html
    

    CopyWebpackPlugin 输出到以下位置:

    预期:

    /public
      /dir-1
        /child-a
          index.html
          page.html
        /child-b
          index.html
          contact.html
      /dir-2
        index.html
    

    /public
      /source
        /dir-1
          /child-a
            index.html
            page.html
          /child-b
            index.html
            contact.html
        /dir-2
          index.html
    

    注意 来源 目录包含在复制目标中。我不明白为什么会包括在内。更重要的是,我需要删除它。如何删除

    3 回复  |  直到 7 年前
        1
  •  30
  •   Stanislav Mayorov    6 年前

    您可以使用 context 参数。

    new CopyWebpackPlugin(
        [{
            context: './source/',
            from: '**/*.html',
            to: './public',
            force: true
        }], {
            copyUnmodified: true
        }
    )
    
        2
  •  2
  •   The Fool    4 年前

    patterns: [
        { from: "src/*.svg",    to: '[name].svg'},
    ]
    
        3
  •  1
  •   fredericrous    3 年前

    我可以复制文件夹 src/pages/Content/lib build/lib 并保持原始结构,配置如下:

        new CopyWebpackPlugin({
          patterns: [
            {
              from: 'src/pages/Content/lib',
              to({ context, absoluteFilename }) {
                return path.join(__dirname, 'build', 'lib', path.relative(context, absoluteFilename));
              },
            },
          ],
        }),
    

    下面的示例页面帮助我了解了如何配置插件: https://webpack.js.org/plugins/copy-webpack-plugin/#copy-in-new-directory

    force: true info: { minimized: true }