2017.3.4
2017.6.6

webpack環境で外出しにしたHTMLファイルを読み込む方法

以前の記事(webpack環境で外出しにしたCSSファイルを読み込む方法) のHTML版になります。

Angular2でのHTMLの指定方法

① .tsファイルに直接書く場合

コンポーネントファイル(test.component.ts)


@Component({
  selector: 'test',
  styles: [require('./test.component.css')],
  template: `<h1>テスト</h1>`
})

② 別途、HTMLファイルに書き出す場合

コンポーネントファイル(test.component.ts)


@Component({
  selector: 'test',
  styles: [require('./test.component.css')],
  templateUrl 'test.component.html'`
})

HTMLファイル(test.component.html)


<h1>テスト</h1>

③ webpackで外出しにしたHTMLファイルを読み込む場合

コンポーネントファイル(test.component.ts)


@Component({
  selector: 'test',
  styles: [require('./test.component.css')],
  template: require('./test.component.html')
})

HTMLに関しては、CSSと違ってraw-loaderで読み込まずとも③の設定だけで最初は問題ありませんでしたが、Angular2のリピート機能「*ngFor=」をHTMLに埋め込むと以下のようなエラーがブラウザのコンソールに出力されて失敗します。


Can't bind to 'ngforOf' since it isn't a known property of

解決方法

こちらも方法としてはCSSと同様、html-loaderではなくraw-loaderでファイルを読み込めばOKでした。

変更前


  module: {
    rules: [
      {
        test: /\.html$/,
        use: [ {
          loader: 'html-loader',
          options: {
            minimize: true
          }
        }],
      }
    ],

変更後


  module: {
    rules: [
      {
        test: /\.html$/,
        use: ['raw-loader'],
      }
    ],

コンポーネント用以外でHTMLファイルをロードする場合は、CSSと同じようにincludeとexcludeで判定すればいいと思います。ただ、公式サイトではhtml-loaderを使っているみたいなので、もしかしたらhtml-loaderでもうまくいく方法があるのかもしれません。

Angular】関連記事