Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save AndrewRayCode/07a5f63e3f5c1b138eef to your computer and use it in GitHub Desktop.

Select an option

Save AndrewRayCode/07a5f63e3f5c1b138eef to your computer and use it in GitHub Desktop.
/**
* What is it:
* Require an image relative to a base image folder and include @2x if it's a retina screen.
* Works with webpack and only requires one image path (as opposed to react-retina-image,
* which requires specifying both regular and @2x paths). Depends on npm package 'is-retina'
* and node's 'path'
* Usage:
* import requireRetina from './require_retina.js'; // this file
* <img src={requireRetina('your_image.png')} />
*/
import isRetina from "is-retina";
import path from "path";
// This will build every image in the image folder into the built directory(!)
// See https://github.com/webpack/docs/wiki/context#requirecontext
let requireImage = require.context("assets/images/", true, /.+\.(png|gif|jpe?g)$/);
// Require an image relative to the above path "assets/images/", and
// require filename@2x (by convention) if in a retina environment
export default function(src) {
let ext = path.extname(src);
let fileName = path.basename(src, ext);
let filePath = path.dirname(src);
return requireImage(
"./" + path.join(filePath, fileName + (isRetina() ? "@2x" : "") + ext )
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment