Reputation: 610
In order to start using react, i added Webpack and Babel to my node app. I imported all my scripts to one script and set it as entry in webpack.config.js which looks like this:
module.exports = {
entry: './src/App.js',
output: {
path: __dirname,
filename: 'app.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
}
};
when starting the webpack-dev-server, the scripts cannot find the images located in my public folder (which is being pointed as the static folder in the server index.js). I tried adding - publicPath: "/public/" in the output but then it couldn't even find app.js anymore. what's the best way of using my images in Webpack?
Upvotes: 1
Views: 6810
Reputation: 3476
Just put them in your source directory and require them!
src/exampleImage.jpg = your image
src/ExampleImage.js:
import React from 'react';
import imageUrl from './exampleImage.jpg';
export default class ExampleImage extends React.Component {
render() {
return <img src={imageUrl} />;
}
}
Add the correct loader to your loaders array (don't forget to npm install file-loader
):
{
test: /\.(jpg|png|gif)$/,
loaders: ['file'],
}
And you're done! Webpack will automatically copy the image over to the right directory (where your built scripts will be) and make sure imageUrl is right and works.
Cool bonus: you can automatically minify images with image-webpack-loader, and do things like automatic filename hashing with file-loader for long-term caching. Just check their documentations for more information!
Upvotes: 4