1

シンプルなHello Worldタイプの Web アプリケーションがあります。「Hello, World!」というテキストを表示するだけです。背景画像付き。アプリは期待どおりに動作しますが、画像がどのようにバンドルされて提供されるかをよりよく理解したいと思います。

を実行するwebpack-dev-serverと、背景画像pattern.svgが次のように出力されることがわかりe78b561561e0911af1eae4c8c3de25c4.svgます。

                               Asset       Size  Chunks             Chunk Names
e78b561561e0911af1eae4c8c3de25c4.svg    27.7 kB          [emitted]
                     index_bundle.js     748 kB       0  [emitted]  main
                          index.html  435 bytes          [emitted]

にアクセスするhttp://localhost:[my-port]/e78b561561e0911af1eae4c8c3de25c4.svgと、画像は期待どおりに表示されます。ただし、フォルダー内の webpack の出力を見ると、次のdist2 つのファイルしか表示されません。

# ls -al dist
total 260
drwxr-xr-x 2 root root     45 Oct 17 15:43 .
drwxr-xr-x 6 root root    132 Oct 17 15:58 ..
-rw-r--r-- 1 root root    435 Oct 17 15:43 index.html
-rw-r--r-- 1 root root 260176 Oct 17 15:43 index_bundle.js

リクエストするとどうなりhttp://localhost:[my-port]/e78b561561e0911af1eae4c8c3de25c4.svgますか? 画像は webpack の出力バンドルのどこにあり、サーバーはどのようにしhttp://localhost:[my-port]/e78b561561e0911af1eae4c8c3de25c4.svgてこの画像にマップすることを認識していますか? 参考までに、以下の関連ファイルの内容を参照してください。

/app/index.html

...
<body>
  <div id='app' />
</body>
...

/app/index.js

var React = require('react');
var ReactDOM = require('react-dom');
require('./styles/main.css');
...

/app/styles/main.css

#app {
  background-image: url('../images/pattern.svg');
}

/webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/app/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: './app/index.js',
  output: {
    path: 'dist',
    filename: 'index_bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      },
      {
        test: /\.(svg)$/i,
        loader: 'file'
      }
    ]
  },
  plugins: [
    HtmlWebpackPluginConfig
  ]
}
4

0 に答える 0