1. ホーム
  2. webpack

[解決済み] Webpack - CopyWebpackPluginを使用してソースから公開ファイルへファイルをコピーする

2022-02-25 22:24:44

質問

Webpackを使用しているアプリがあります。このアプリでは、いくつかの静的な .html ファイルをさまざまなディレクトリから source ディレクトリの同じ階層に public ディレクトリを作成します。これを実現するために、私は CopyWebpackPlugin . この時、私のwebpack.config.jsは以下のようなファイルになっています。

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 をコマンドラインから実行すると、すべてが思い通りに動作します。HTMLファイルは、そのディレクトリを含めて、正常に public ディレクトリを作成します。ただし、コピー時にコピー元のディレクトリ名が含まれます。例えば、私のディレクトリ構造が次のようなものであった場合。

/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

しかし、実際に取得できているのは

actualを使用します。

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

がどのように source ディレクトリがコピー対象に含まれています。なぜこれが含まれているのか理解できません。もっと重要なのは、これを削除する必要があることです。どのようにすれば source ディレクトリをターゲット内のパスから削除してください。

解決方法は?

を使用することができます。 コンテキスト パラメータを指定します。

new CopyWebpackPlugin(
    [{
        context: './source/',
        from: '**/*.html',
        to: './public',
        force: true
    }], {
        copyUnmodified: true
    }
)