Webpack第5章(plugin)


Webpackの2つの拡張形式

  • loader:最終出力時にモジュールを使用する
  • plugin:変形が最終的に生成するもの(複雑、自由)
  • なぜpluginを使うのか


    ターゲットを自動的に作成する場合

    plugin(html-webpack)の使用

    npm install --save-dev html-webpack-plugin運転命令
    index.htmlとサブインデックス.htmlをソースコードに移動し、コードを変更

    index.html
    <html>
    <head>
        <meta charset="utf-8"/>
    
    </head>
    <body>
        <div id="root"></div>
        <a href="subindex.html">index</a>
    </body>
    </html>
    
    subindex.html
    <html>
    <head>
        <meta charset="utf-8"/>
    
    </head>
    <body>
        <div id="root"></div>
        <a href="index.html">subindex</a>
    </body>
    </html>
    

    Webpack.config.jsにpluginを挿入する

  • const HtmlWebpackPlugin = require('html-webpack-plugin');コード追加
  • 以下のコードを追加
  • npx webpack命令実行
  • plugins : [
        new HtmlWebpackPlugin({
          template:'./source/index.html',
          filename:'./index.html',
          chunks:['index']
        }),
        new HtmlWebpackPlugin({
          template:'./source/subindex.html',
          filename:'./subindex.html',
          chunks:['subindex']
        })
      ]

    webpack.config.jsコード

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      mode:"development",
      entry : {
        index : "./source/index.js",
        subindex :"./source/subindex.js"
      },
      output : {
        path:path.resolve(__dirname,"public"),
        filename : '[name]_bundle.js'
      },
      module:{
        rules:[
          {
            test:/\.css$/,
            use:[
              'style-loader',
              'css-loader'
            ]
          }
        ]
      },
      plugins : [
        new HtmlWebpackPlugin({
          template:'./source/index.html',
          filename:'./index.html',
          chunks:['index']
        }),
        new HtmlWebpackPlugin({
          template:'./source/subindex.html',
          filename:'./subindex.html',
          chunks:['subindex']
        })
      ]
    }

    結果



    pluginとコマンドを使用して必要なファイルを生成し、それぞれのhtmlとjsを生成できます.

    ソース


    生活コード