webapackを勉強しているのですが、設定ファイルを共通化して実行できるようにしたいです。
ここの設定がdev, prodで共通しているのでwebpack.common.jsに入れたいが、入れるとエラーが出力される。現状はdev, prodそれぞれにdevServerの設定を書く事でエラーは出ていない。
詳しい方、教えて頂けると幸いです。宜しくお願い致します。
エラー内容
✖ 「wdm」: Error: Conflict: Multiple chunks emit assets to the same filename undefined.js (chunks 143 and 435)
at /src/node_modules/webpack/lib/Compilation.js:3877:12
at /src/node_modules/webpack/lib/Cache.js:93:5
at Hook.eval [as callAsync] (eval at create (/src/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
at Cache.get (/src/node_modules/webpack/lib/Cache.js:75:18)
at ItemCacheFacade.get (/src/node_modules/webpack/lib/CacheFacade.js:117:15)
at /src/node_modules/webpack/lib/Compilation.js:3823:22
at arrayEach (/src/node_modules/neo-async/async.js:2405:9)
at Object.each (/src/node_modules/neo-async/async.js:2846:9)
at /src/node_modules/webpack/lib/Compilation.js:3812:14
at symbolIterator (/src/node_modules/neo-async/async.js:3482:9)
ℹ 「wdm」: wait until bundle finished: /
ℹ 「wdm」: wait until bundle finished: /
共通化したい設定
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 8080,
host: '0.0.0.0',
watchOptions: {
ignored: /node_modules/
}
},
webpack.common.js
const path = require('path')
// jsファイルにバンドルされるはずのcssを分離できる。cssに変更がない場合はキャッシュを利用できるので商用環境では分離をオススメする。
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// const webpack = require('webpack')
// こうする事で個別でimport出来る。分割代入
const { ProvidePlugin } = require('webpack')
module.exports = ({ outputFile, assetFile }) => ({
// 作業ディレクトリがある場合はentryの書き方が変わる
context: `${__dirname}/src`,
// entry: './index.js',
// joinを使用するとOSの環境に合わせてパスをいい感じに設定してくれる。
entry: {
app: path.join(__dirname, '/src', 'app.js'),
sub: path.join(__dirname, '/src', 'sub.js')
},
// defaultの設定つまりあってもなくても一緒
// ファイルの起点を設定する。
// entry: './src/index.js',
// ここは絶対パスで指定する必要がある。
output: {
// path: `${__dirname}/dist`,
path: path.join(__dirname, '/dist'),
filename: `${outputFile}.js`,
assetModuleFilename: `images/${assetFile}[ext]`, // 分割
},
// useはしたから実行されていく。
// sassをcssに変換 → cssをバンドル → htmlにstyleタグを使ってcssを記述する。順番で実行される。
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
// // eslint導入方法
// use:[
// // 'style-loader',
// 'babel-loader',
// 'eslint-loader'
// ],
loader: 'babel-loader'
},
{
enforce: 'pre',
test:/\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
// eslintのfixオプションをonにするルールに基づいてコードを整形してくれる。
options: {
fix: true,
}
},
{
test:/\.scss$/,
use:[
// 'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.(ico|svg|jpe?g|png|webp)$/,
type: "asset/resource", // <--- 'file-loader'
// または
// type: 'asset/inline', // <--- 'url-loader'
},
{
// htmlWebpackPluginと併用しないと動作しない
test: /\.html$/,
use: ['html-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: `${outputFile}.css`, // 分割
// chunkFilename: '[name].[hash].css'
}),
// よく使用するモジュールをimportせずにグローバルにバンドルする事ができる。
// これによってapp.js, sub.jsでjqueryが使用できる。
new ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
// オリジナル関数をimportなしで使えるようにする。
utils: [path.resolve(__dirname, 'src/utils'), 'default']
})
],
optimization: {
splitChunks: {
// chunksがasyncだとダイナックimportと呼ばれる非同期のimport方法のみに設定が適用される。
// import('./app.scss')
// allは普通のimportとダイナミックを分けずにimportする。
chunks: 'all',
minSize: 0,
cacheGroups: {
defaultVendors: {
name: 'vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
},
// オリジナルの関数をキャッシュに追加する。
utils: {
name: 'utils',
test: /src[\\/]utils/
},
default: false,
}
}
}
})
webpack.dev.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { merge } = require('webpack-merge')
const commonConf = require('./webpack.common')
const outputFile = '[name]'
const assetFile = '[name]'
module.exports = () => merge(commonConf({ outputFile, assetFile }), {
mode: 'development', //分割
// これを使用するとchromeの検証でビルド前のファイルも確認できるのでデバックが取りやすくなる。
devtool: 'source-map', // 分割
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 8080,
host: '0.0.0.0',
watchOptions: {
ignored: /node_modules/
}
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, '/src', 'index.html'),
inject: 'body' // 分割
})
]
})
webpack.prod.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { merge } = require('webpack-merge')
const commonConf = require('./webpack.common')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const outputFile = '[name].[chunkhash]'
const assetFile = '[contenthash]'
module.exports = () => merge(commonConf({ outputFile, assetFile }), {
mode: 'production', //分割
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 8080,
host: '0.0.0.0',
watchOptions: {
ignored: /node_modules/
}
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, '/src', 'index.html'),
inject: 'body', // 分割
minify: {
collapseWhitespace: true,
keepClosingSlash: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
})
],
optimization: {
minimizer: [
(compiler) => {
const TerserPlugin = require('terser-webpack-plugin')
new TerserPlugin({
terserOptions: {
compress: {},
mangle: true
}
}).apply(compiler)
},
new CssMinimizerPlugin(),
]
}
})
package.json
ここでコンパイルとdevServer立てるコマンドを作成している。
{
"name": "src",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"cleanup": "rimraf ./dist",
"dev": "npm run webpack:dev && npm run webpack:server-dev",
"prod": "npm run webpack:prod && npm run webpack:server-prod",
"webpack:server-dev": "webpack server --config ./webpack.dev.js",
"webpack:server-prod": "webpack server --config ./webpack.prod.js",
"webpack:dev": "npm run cleanup && webpack --config ./webpack.dev.js",
"webpack:prod": "npm run cleanup && webpack --config ./webpack.prod.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.15.0",
"@babel/preset-env": "^7.15.0",
"autoprefixer": "^10.3.1",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"core-js": "^3.16.1",
"css-loader": "^6.2.0",
"css-minimizer-webpack-plugin": "^3.0.2",
"eslint": "^7.32.0",
"eslint-loader": "^4.0.2",
"html-loader": "^2.1.2",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.2.0",
"postcss-loader": "^6.1.1",
"regenerator-runtime": "^0.13.9",
"rimraf": "^3.0.2",
"sass": "^1.37.5",
"sass-loader": "^12.1.0",
"style-loader": "^3.2.1",
"webpack": "^5.49.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.8.0"
},
"dependencies": {
"jquery": "^3.6.0"
}
}