Skip to content

Instantly share code, notes, and snippets.

@MadRiver44
Last active November 7, 2017 21:54
Show Gist options
  • Save MadRiver44/13c19fb4d30308e773fe6b34118b7b1d to your computer and use it in GitHub Desktop.
Save MadRiver44/13c19fb4d30308e773fe6b34118b7b1d to your computer and use it in GitHub Desktop.
Adding images to react with webpack

Adding images to a React app with Webpack

Setup

  • npm install --save-dev file-loader
  • npm install --save-dev css-loader

Remember, loaders are transformations that are applied on the source code of the module. They allow you to pre-process files as you import or load them. Loaders similar to other build tools perform tasks and handle front end build steps. For this gist loaders allow the import of CSS files directly into javascript modules.

Now add to the webpack module.rules property

},
 module: {
  rules: [
    {
      test: /\.css$/,
      use: [
        'style-loader',
        'css-loader'
      ]
    },
   {
     test: /\.(png|svg|jpg|gif)$/,
     use: [
       'file-loader'
     ]
   },

For example, here is a simple site structure and we will import a picture from Portfolio/public/images/hiking.jpg and use it in the Home.js component.

*Portfilio app Components About.js App.js Header.js Home.js Links.js Nav.js Projects.js index.js node_modules public images hiking.jpg package-lock.json .babelrc package.json webpack.config.js

Home.js

   import Hiking from '../../public/images/hiking.jpg';
   /* in a div somewhere add Hiking var to <img src={Hiking}...*/
   
   const Home = () => {
      return (
      <div>
        <img className="hiking" src={Hiking} alt={'hiking pic'} />
       </div>

When Hiking is imported, that image will be processed and added to the output directory and the Hiking variable will contain the final url of that image after processing. The same is true if using the css-loader and you need a background image in the css file.

Documentation

webpack docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment