1

I have a simple Hello World-type web application. It simply displays the text "Hello, World!" with a background image. The app works as expected, but I would like to better understand how the image is bundled and served.

When I run webpack-dev-server, I see that my background image pattern.svg is emitted as 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]

If I visit http://localhost:[my-port]/e78b561561e0911af1eae4c8c3de25c4.svg, the image is served as expected. However, if I look at webpack's output in my dist folder, I only see two files:

# 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

What happens when I request http://localhost:[my-port]/e78b561561e0911af1eae4c8c3de25c4.svg? Where does the image live in webpack's output bundle, and how does the server know to map http://localhost:[my-port]/e78b561561e0911af1eae4c8c3de25c4.svg to this image? For reference, see contents of relevant files below.

/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
  ]
}
Matthew
  • 28,056
  • 26
  • 104
  • 170

0 Answers0