copy-webpack-pluginを使ってdevelopmentとproductionのビルドを行う
やりたいこと
開発時 (development)
$ npm start
ビルド時 (production)
$ npm run build
public/index.htmlとsrc/index.jsをもとに、dist/index.htmlとdist/bundle.jsを作成したい
code:ディレクトリ構成
.
├── dist
│ ├── bundle.js
│ └── index.html
├── node_modules
├── package-lock.json
├── package.json
├── public
│ └── index.html
├── src
│ └── index.js
└── webpack.config.js
環境
npm 6.14.5
webpack 4.43.0
設定
code:sh
npm install --save-dev webpack webpack-cli webpack-dev-server copy-webpack-plugin
code:package.json
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack --mode production"
},
code:webpack.config.js
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const srcPath = path.join(__dirname, "src");
const publicPath = path.join(__dirname, "public");
const distPath = path.join(__dirname, "dist");
module.exports = {
entry: path.join(srcPath, "index.js"),
output: {
filename: "bundle.js",
path: distPath,
},
devServer: {
contentBase: publicPath,
},
plugins: [
new CopyPlugin({
patterns: from: publicPath, to: distPath },
}),
],
};
注意点
index.htmlにあらかじめscriptタグを追加しておく必要がある
code:index.html
<script src="bundle.js"></script>
試行錯誤中のメモ
npm start (npx webpack-dev-server)で出たエラーログ
code:sh
ValidationError: Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options0 misses the property 'patterns'. patternsなしに動いている日本語の記事が結構あって、それ参考にしてたけど全く動かなかった
公式に合わせて「patterns」を入れたら動いた
参考
関連