0.1.20 • Published 5 years ago

react-sharp-loader v0.1.20

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

React-sharp-loader

image file > webpack loader > react component > :sparkles:

This loader is in test stage. I check if this approach makes sense. That means there can be a lot of changes from version to version.

Features

  • <MyImage /> simple usage.
  • support for emotion 10 (but not required)
  • all in one component: placeholder, srcset, fallback
  • supports server-side rendering
  • default config should be enough for most, but..
  • if you want, you can change sharp config, or even inner functions.

Future

not before version 0.2

  • Access from react to: metadata, configs, dominant/vibrant colors etc.
  • limit: 10000 bytes, if less then that, loader output only base64.
  • better support for images lower size then declared in presets
  • cache for speed up
  • lazy load
  • Support for height and max-height css

Install:

yarn add react-sharp-loader

Usage

Illustrative example

Death simple import responsive images with react component

import React from 'react'
import MyImage from 'imageFile.jpg'

export default () => (
  <div>
    <MyImage />
  </div>
)

And that’s all. In DOM you have similar structure to this one:

<div>
  <img src="data:base64 .. placeholder" alt="" />
  <picture>
    <source
      type="image/webp"
      setsrc="image.300.webp 300w, image.600.webp 600w"
    />
    <img
      setsrc="image.300.jpg 300w, image.600.jpg 600w"
      src="fallback.jpg"
      alt=""
    />
  </picture>
</div>

Note: If you don't like output react component, you can declare your own function to create component like you want to have.

import examples:

import MyImage from 'image.jpg'
import MyImage from 'image.jpg?preset=myPresetName'

Usage component:

<MyImage alt="Lorem ipsum" />

// emotion 10+
<MyImage css={css`border: solid 1px red`} />

Webpack:

///...
module: {
  rules: [
    // ...
    {
      test: /\.(jpe?g|png|webp|gif|tiff?|svg)$/,
      loader: require.resolve('react-sharp-loader'),
    },
    // ...
  ],
},
// ...

More advanced webpack example:

This loader use Sharp to image conversion. Mode information about opbtions in Sharp documentation.

{
  test: /\.(jpe?g|png|webp|gif|tiff?|svg)$/,
  loader: require.resolve('react-sharp-loader'),
  options: {
    emitFile: !isSSR,
    publicPath: paths.url.images,
    outputPath: 'images',
    name: '[name].[hash:8].[ext]',
    cacheDirectory: true,
    config: {
      grayscale: true,
    },

    presets: {
      default: {
        srcset: [
          {
            format: ['webp', 'jpg'], // order have a meaning
            width: [150, 300, 450, 600, 900, 1200, 1600],
          },
        ],
        fallback: [{ width: 1600 }],
        placeholder: [{ width: 50, base64: true }],
      },
    },
  },
},

Sharp config examples:

[{ width: [150, 300] }]

[{ width: [10, 20], quality: [65, 80] }]

{
  '*.jpg': {
    width: [600, 900]
  },
  'name.png': {
    widht: 400,
  },
  '.webp': [
    { width: 400, grayscale: true },
    { width: 400, grayscale: false },
  ],
  '*': {
    width: 400, grayscale: [true, false] },
  },
}

[
  {
    name: 'specialNme.jpg',
    width: [150, 300],
  },
    width: [150, 300, 600],
    fotmat: ['jpeg', 'webp'],
  },
  {
    base64: true,
    width: 50,
    format: 'jpeg',
  }
]

Notation like this

[{ width: [10, 20], quality: [65, 80] }]

will give you such files:

[
  { width: 10, quality: 65 },
  { width: 10, quality: 80 },
  { width: 20, quality: 65 },
  { width: 20, quality: 80 },
]

API

React Image Component

PropertyTypeDefaultDescription
altStringAlt for img tag.
sizesString100vwSizes for img and picture tag.
classNameStringContainer class.
imgClassNameStringimg tag class.

Webpack loader options

OptionTypeDefaultDescription
nameStringname.hash:8.extFile name for convered image.
emitFileBoolean, FunctiontrueWrite file on disk (Useful in ssr). or function to do that.
cacheDirectoryString BooleantrueCache file directory on disk.
publicPathStringurl directory.
outputPathStringOutput file on disk.
configObjectCommon config for all files.
limitNumber10000If file size is less than than, loader export img tag with base64 source, without any setsrc, placholders etc.
presetsObject{ default }Configs for sharp image converter.
defaultPresetStringdefaultDefault preset to use if no other is specified.
createHashFunctionGenerate hash for input file.
applyConfigFunctionApply config to sharp image instance.
createPathFunctionCreate info about fileName, dir, mime etc.
createBase64FunctionCreate base64 data.
buildTargetObjectFunctionSort result files to target objects.
modularizeFunctionCreate react component and other information to export.
stringifyFunctionExport data.

Preset options

/// ...
presets: {
  [myPresetName]: {
    [target]: sharpConfig,
  },
},
TargetTypeDefaultDescription
srcsetObject{ ... }Sharp config for srcset. The last one is used in img tag, others is for picture tag
fallbackObject{ width: 1600 }Sharp config for img source.
placeholderObject{ width: 50, base64: true }Sharp config for create placeholder img tag.
paletteObject{ width: 300 }Sharp config for generate dominant colors.
outputPathStringOutput file on disk.
configObjectCommon config for all files.
limitNumber10000If file size is less than than, loader export img tag with base64 source, without any setsrc, placholders etc.
presetsObject{ default }Configs for sharp image converter.
defaultPresetStringdefaultDefault preset to use if no other is specified.

Webpack default options in code:

name: '[name].[hash:8].[ext]',
emitFile: true,
cacheDirectory: true,
outputPath: '',
config: {},
limit: 10000,
palette: true,
presets: {
  default: {
    srcset: [
      {
        format: ['webp', 'jpg'], // order have a meaning
        width: [150, 300, 450, 600, 900, 1200, 1600],
      },
    ],
    fallback: [{ width: 1600 }],
    placeholder: [{ width: 50, base64: true }],
    palette: [{ width: 300 }],
  },
},
defaultPreset: 'default',

Docker

If you want use Sharp with Docker, this code can halp. Paste it to Dockefile:

FROM node:8-alpine

RUN apk add vips-dev fftw-dev --update-cache --repository https://dl-3.alpinelinux.org/alpine/edge/testing/ && \
    apk update && \
    apk upgrade --update-cache --available && \
    apk add ca-certificates \
        xpdf \
        vips \
        vips-dev \
        python2 \
        git \
        make \
        g++

RUN rm -rf /var/cache/apk/*

Issues

If you find a bug, please file an issue on our issue tracker on GitHub.

License

MIT

0.1.20

5 years ago

0.1.19

5 years ago

0.1.18

5 years ago

0.1.17

5 years ago

0.1.16

5 years ago

0.1.15

5 years ago

0.1.14

5 years ago

0.1.13

5 years ago

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago