以下は、基本的な構成の webpack.config.js
ファイルです。CSSの読み込み、HTMLテンプレートの自動生成、開発サーバーの設定まで含んでおり、フロントエンド開発におけるモダンな開発環境を構築できます。
まず、ファイルの内容を提示し、その後に各セクションごとの解説を行います。
webpack.config.js 全体
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
}),
],
devServer: {
static: './dist',
open: true,
},
mode: 'development',
};
各セクションの解説
✅ const path = require('path');
Node.jsの標準モジュールで、ファイルパスの操作に使用します。
✅ const HtmlWebpackPlugin = require('html-webpack-plugin');
Webpack用のプラグイン。テンプレートとなるHTMLファイルにバンドル済みのJSファイル(例: bundle.js
)を自動で挿入してくれます。
✅ entry
entry: './src/index.js',
Webpackが依存関係の解決を始めるエントリーポイント。プロジェクトの主なJSファイルを指定します。
✅ output
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
-
filename
: 出力するバンドルファイル名。 -
path
: 出力先の絶対パス。 -
clean
: 出力前にdist
フォルダをクリーン(削除)します。
✅ module.rules
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
-
test
: 対象となるファイル(ここでは.css
)。 -
use
: 適用するローダーの配列(順序が重要)。-
css-loader
: CSSをJSで扱えるようにする。 -
style-loader
: JS内のCSSを<style>
タグとしてHTMLに挿入。
-
✅ plugins
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
}),
],
- HTMLファイルを自動生成。
-
template
に指定したファイルをベースに、バンドルしたJSを挿入したHTMLを出力。
✅ devServer
devServer: {
static: './dist',
open: true,
},
-
static
: サーバーが提供するファイルのルートディレクトリ。 -
open
: サーバー起動時にブラウザを自動で開く。
✅ mode
mode: 'development',
-
'development'
: 開発モード(ソースマップあり・圧縮なし)。 -
'production'
: 本番モード(圧縮や最適化が有効)。
✅ まとめ
この設定ファイルは、次のような基本構成を持ったモダンな開発環境を提供します:
-
index.js
からJSをバンドル - CSSの読み込みと挿入をサポート
- HTMLファイルを自動生成
- 開発サーバーの起動 (
npm start
) - 本番ビルドにも対応 (
npm run build
)
シンプルかつ拡張性のある構成なので、これからWebpackを使ってフロントエンド開発を始めたい方におすすめです。