これまではwebpackを使用してバンドルファイルを生成するとcssもjsファイルにバンドルされて出力されていました。
この場合、厳格なContent Security Policyに適していないので、今回はwebpack実行時にcssをcssファイルにして出力します。
なお、前回までの内容の続きになります。
使用するプラグイン
今回は以下のプラグインを使用します。
・プラグイン
mini-css-extract-plugin
構成
前回と同様の構成になります。各ファイルの内容は前回と変わりありません。
.
├── node_modules
├── package-lock.json
├── package.json
├── src
│ ├── js
│ │ ├── index.js
│ │ └── test.mjs
│ ├── css
│ │ └── style.css
│ └── index.html
└── webpack.config.js
インストール
npmでプラグインをインストールします。
npm install --save-dev mini-css-extract-plugin設定
プラグインを設定します。スタイルローダー(style-loader)の記載を削除し、mini-css-extract-plugin を使用する点に注意して下さい。
'use strict'
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: 'development',
entry: './src/js/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({ template: './src/index.html' }),
new MiniCssExtractPlugin()
],
module: {
rules: [
{
test: /\.(css)$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
}
]
}
]
}
}webpackの実行
webpackを実行します。
npx webpack前回と同様ですが、distディレクトリ以下にmain.jsとindex.htmlが出力されます。今回はさらにmain.cssが出力されます。
ブラウザからdistディレクトリ以下にあるindex.htmlを開きます。
h1タグの文字が赤文字になっている事が確認出来ます。

最後に
特にありません。