André Kuhlmann
André Kuhlmann

Reputation: 4678

Ideas for handling images with webpack

This is my current project setup:

dist/
├── bundle.js
└── index.html
src/
├── main.js
├── img/
│    └── icon.svg
├── js/
└── styles/
     └── page.css
webpack.config.js

When I want to reference an image inside of my index.html file

<img src="img/icon.svg">

I first need to require it inside my main.js file in order to get processed and build inside this dist/img/ directory, when I now want to use the icon in my css as well I get referencing issues. Hope you could give me some advice on how to optimize my setup.

const path = require('path');

const excludeDirectorys = path.resolve(__dirname, 'node_modules');

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: 'dist/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      // => JS Loader
      { test: /\.js$/,include: path.resolve(__dirname, 'src'), exclude: excludeDirectorys, loader: 'babel-loader', query: { presets: ['es2015']} },
      // => CSS Loader
      { test: /\.css$/, exclude: excludeDirectorys, loaders: ['style-loader', 'css-loader', 'autoprefixer-loader'] },
      // => SASS Loader
      { test: /\.(sass|scss)$/, exclude: excludeDirectorys, loaders: ['style-loader', 'css-loader', 'autoprefixer-loader', 'sass-loader'] },
      // => Image Loader
      { test: /\.(jpe?g|png|gif|svg)$/i, exclude: excludeDirectorys, loaders: ['file-loader?name=./img/[name].[ext]', 'image-webpack?'] }
    ]
  },
};

Upvotes: 0

Views: 281

Answers (1)

Andy Ray
Andy Ray

Reputation: 32076

If you have a top level static HTML file, I would use the html-webpack-plugin, which will let you do things like:

<img src="<%= require('../path/to/icon.svg') %>" />

Upvotes: 1

Related Questions