LoginSignup
19

More than 5 years have passed since last update.

webpack と HTML と CSS

Last updated at Posted at 2017-10-14

動機

webpackはJavaScriptだけでなく、htmlやCSSの活用ができる。
例えばcssの外部読み込みなど。

HTML Webpack Plugin

導入

$ npm install html-webpack-plugin --save-dev

使い方

webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

{
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: 'public/index.html'
    })
  ]
}

解説

  • inject: true
    すべてのアセットを指定されたものに挿入する
  • template: path
    指定した自作htmlに適用する。
    pathの指定がなければ勝手にhtmlを生成する。

使い所

interpolate-html-pluginと連携する。

interpolate-html-plugin

導入

yarn add interpolate-html-plugin --dev

使い方

webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InterpolateHtmlPlugin = require('interpolate-html-plugin');

{
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  module: {
    rules: [
      {
        oneOf: [
          {
            test: /\.html/,
            loader: require.resolve('html-loader'),
          },
          {...}
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: 'public/index.html'
    }),
    new InterpolateHtmlPlugin({
      'bootstrap_css_cdn': 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css'
    })
  ]
}
public/index.html
<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="sample">
    <meta httpEquiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" type="text/css" href="%bootstrap_css_cdn%">
    <title>SAMPLE</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <main><main>
  </body>
</html>

解説

  • env: string
    html内にある%foo%の記述を置き換えてくれる。

使い所

とりあえずindex.jsあたりでcssをimportすることを辞める手段の一つ。
Node.jsの実行時の環境変数はprocces.env: {...}なので、うまく捌いてprocces.envの中身を与えれば環境ごとで違う値をinjectionすることが出来るので、package.jsonのscriptsあたりでこの値を管理できる。

最後に

html-loaderの記述を忘れないでください。公式には記載されて居ないので見落とすとハマると思います。
まだまだbundle.jsの容量を減らす術はあります。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19