🖼 Image Presets for Vite.js apps

Overview


vite-plugin-image-presets

Image Presets for Vite.js apps


This Vite plugin allows you to define presets for image processing using Sharp, allowing you to optimize, resize, and process images consistently and with ease.

Demo 🖼

Installation 💿

npm install -D vite-plugin-image-presets # pnpm, yarn

Configuration ⚙️

Add it to your plugins in vite.config.ts

import { defineConfig } from 'vite'
import imagePresets, { widthPreset } from 'vite-plugin-image-presets' 

export default defineConfig({
  plugins: [
    imagePresets({
      thumbnail: widthPreset({
        class: 'img thumb',
        loading: 'lazy',
        widths: [48, 96],
        formats: {
          webp: { quality: 50 },
          jpg: { quality: 70 },
        },
      }),
    }),
  ],
})

Usage 🚀

Use the preset query parameter to obtain an array of source and img attrs:

import thumbnails from '~/images/logo.jpg?preset=thumbnail'

expect(thumbnails).toEqual([
  {
    type: 'image/webp',
    srcset: '/assets/logo.ffc730c4.webp 48w, /assets/logo.1f874174.webp 96w',
  },
  {
    type: 'image/jpeg',
    srcset: '/assets/logo.063759b1.jpeg 48w, /assets/logo.81d93491.jpeg 96w',
    src: '/assets/logo.81d93491.jpeg',
    class: 'img thumb',
    loading: 'lazy',
  },
])

You can also use the src and srcset query parameters for direct usage:

import srcset from '~/images/logo.jpg?preset=thumbnail&srcset'

expect(srcset).toEqual('/assets/logo.063759b1.jpeg 48w, /assets/logo.81d93491.jpeg 96w')


import src from '~/images/logo.jpg?preset=thumbnail&src'

expect(src).toEqual('/assets/logo.81d93491.jpeg')

Check the example for additional usage information and different preset examples, or see it live.

Documentation 📖

Additional usage documentation coming soon.

In the meantime, check the @islands/images module for îles.

Acknowledgements

  • sharp: High performance Node.js image processing
  • vite-imagetools: The middleware used in development is based on this nice library.

The hdPreset is based on the following article by Jake Archibald:

License

This library is available as open source under the terms of the MIT License.

Comments
  • Use `rollupOptions.options.assetFileNames` when specified in the Vite config

    Use `rollupOptions.options.assetFileNames` when specified in the Vite config

    Typically in vite we use build.rollupOptions.output.assetFileNames to tweak output directory and file names, like:

                rollupOptions: {
                    output: {
                        assetFileNames: (asset) => {
                            if (
                                ['.jpg', '.png', '.svg', '.avif', '.webp'].some((ext) =>
                                    asset.name?.endsWith(ext),
                                )
                            ) {
                                return 'images/[name]-[hash][extname]';
                            }
                            return 'assets/[name]-[hash][extname]';  // for other assets like fonts and audios etc.
                        },
                    },
    

    While this plugin provides an assetsDir option, it should still conform to the idiom above when assetsDir is not specified. But unfortunately that's not the current behavior.

    I can submit a PR for this if feasible.

    enhancement 
    opened by lsdsjy 5
  • Cached images are re-written (and not used from cache) on each netlify deployment

    Cached images are re-written (and not used from cache) on each netlify deployment

    When we deploy https://github.com/mseele/sve-website via netlify, the image are re-written each time and the image cache is ignored. Please see the attached build log.

    If there is anything I can do to help detecting the problem, please let me know.

    opened by mseele 2
  • Update NPM package

    Update NPM package

    A security issue #14 is fixed in the pull #15 and it is also merged but this package is not yet updated in NPM registry. Please publish the the updated repo in NPM so all the dependent projects can benefited

    opened by Rajaniraiyn 1
  • Animated images Support

    Animated images Support

    Sharp supports animated option to read all frames of an animated png, gif, avif, webp image formats. But, there is no way to use that option in presets. Now by default all animated images are converted to non-animated upon any conversion.

    https://github.com/Rajaniraiyn/modern-web-boilerplate , this project uses apng but upon using this plugin it is converted into non-animated form.

    Not only this. It would be nicer to enable an option to parse custom options to sharp

    opened by Rajaniraiyn 1
  • Add support for dynamic images

    Add support for dynamic images

    Is there any possibility to load dynamic images? I have the following use case: I load a list of events from my headless cms. All events have an attribute title image that is named like an image i have in my assets folder. Now i want to use vite-plugin-image-presets with the picture vue sfc and the image described in the event attribute. Is there any pattern i can use to do this?

    My workaround is a sfc called DynamicPicture that looks like this:

    <template>
      <Picture :src="src" />
    </template>
    
    <script setup lang="ts">
    import { computed } from 'vue'
    
    import event_img_1 from '@/assets/events/event_img_1.jpg?preset=full'
    import event_img_2 from '@/assets/events/event_img_2.jpg?preset=full'
    import event_img_3 from '@/assets/events/event_img_3.jpg?preset=full'
    
    let assets = new Map<string, any>([
      ['event_img_1.jpg', event_img_1],
      ['event_img_2.jpg', event_img_2],
      ['event_img_3.jpg', event_img_3],
    ])
    
    const props = defineProps({
      name: {
        type: String,
        required: true,
      },
    })
    
    const src = computed(() => assets.get(props.name))
    </script>
    

    It works. But i need to add a line of code every time i add a new event image into the assets directory (what happens sometimes).

    opened by mseele 1
  • Usage in raw HTML/Twig

    Usage in raw HTML/Twig

    Hi,

    It looks like a great plugin ! Sorry if I misunderstand something, but I can't find how to use this in a raw HTML or a Twig template. Is this something possible ?

    Best.

    opened by Nkzq 1
  • Possible vulnerability in sharp at 'npm install' time if an attacker has control over build environment

    Possible vulnerability in sharp at 'npm install' time if an attacker has control over build environment

    There's a possible vulnerability in logic that is run only at npm install time when installing versions of sharp prior to the latest v0.30.5.

    This is not part of any runtime code, does not affect Windows users at all, and is unlikely to affect anyone that already cares about the security of their build environment. However, out of an abundance of caution, I've created this advisory.

    If an attacker has the ability to set the value of the PKG_CONFIG_PATH environment variable in a build environment then they might be able to use this to inject an arbitrary command at npm install time.

    I've used the Common Vulnerability Scoring System (CVSS) calculator to determine the maximum possible impact, which suggests a "medium" score of 5.9, but for most people the real impact will be dealing with the noise from automated security tooling that this advisory will bring.

    AV:L/AC:L/PR:H/UI:R/S:U/C:H/I:H/A:H/E:P/RL:O/RC:C/CR:X/IR:X/AR:X/MAV:X/MAC:X/MPR:X/MUI:R/MS:X/MC:X/MI:X/MA:X

    This problem was fixed in commit a6aeef6 and published as part of sharp v0.30.5.

    opened by Rajaniraiyn 0
  • enhancement: string as the default export if the preset only defines srcset

    enhancement: string as the default export if the preset only defines srcset

    Description 📖

    Currently the default export for preset imports is ImageSource[]. This allows presets to define additional source tags, with different formats, conditional widths and densities, etc.

    For presets that define a single ImageSource that only contains srcsets, it would be convenient for the default export to be a string.

    That would make it work out of the box in img and source tags in HTML and Vue SFCs, where src and srcset are already extracted as imports.

    enhancement 
    opened by ElMassimo 0
  • [Feature Request] Include generated image dimensions

    [Feature Request] Include generated image dimensions

    Taking the example from the readme...

    widthPreset({
      class: 'img thumb',
      loading: 'lazy',
      widths: [48, 96],
      formats: {
        webp: { quality: 50 },
        jpg: { quality: 70 }
      }
    })
    

    it would be great to have a width and height attributes to spread onto the <img> in order to give it the correct intrinsic dimensions and reserve the correct amount of space when loading to avoid layout shifts, e.g. assuming a 100x150 source image

    expect(thumbnails).toEqual([
      {
        type: 'image/webp',
        srcset: '/assets/logo.ffc730c4.webp 48w, /assets/logo.1f874174.webp 96w',
      },
      {
        type: 'image/jpeg',
        srcset: '/assets/logo.063759b1.jpeg 48w, /assets/logo.81d93491.jpeg 96w',
        src: '/assets/logo.81d93491.jpeg',
        class: 'img thumb',
        loading: 'lazy',
        
        // width and height of the generated image used for `src`
        width: 96,
        height: 144,
      },
    ])
    
    enhancement 
    opened by bensmithett 2
  • [Feature Request] Default preset

    [Feature Request] Default preset

    It would be nice if there were a way to specify a default preset so every import didn't need the query string.

    Maybe something like this...

        imagePresets({
          'default': widthPreset({
            widths: [425, 1024, 1200],
            formats: {
              webp: { quality: 100 },
              png: { quality: 100 }
            }
          })
        }),
    

    Or this...

        imagePresets({
          'foobar': widthPreset({
            default: true,
            widths: [425, 1024, 1200],
            formats: {
              webp: { quality: 100 },
              png: { quality: 100 }
            }
          })
        }),
    

    Great plugin btw 👍 It's saved me a lot of time already.

    enhancement 
    opened by whaaaley 1
Vue 3 + Vite + SSR template based on Vite Plugin SSR and inspired by Vitesse

Vite Vue SSR Starter Vue 3 + Vite + SSR template based on Vite Plugin SSR and inspired by Vitesse Features ⚡️ Vue 3, Vite 2, TypeScript ?? Domain-Driv

Oleg Koval 10 Aug 2, 2022
Integrate Tauri in a Vite project to build cross-platform apps.

vite-plugin-tauri Integrate Tauri in a Vite project to build cross-platform apps Install Make sure to setup your environment for Tauri development. Th

Amr Bashir 95 Dec 15, 2022
A template repository / quick start to build Azure Static Web Apps with a Node.js function. It uses Vue.js v3, Vue Router, Vuex, and Vite.js.

Azure Static Web App Template with Node.js API This is a template repository for creating Azure Static Web Apps that comes pre-configured with: Vue.js

Marc Duiker 6 Jun 25, 2022
A Marko plugin for Vite

@marko/vite A Marko plugin for Vite. Installation npm install @marko/vite Example config import { defineConfig } from "vite"; import marko from "@mark

Marko 49 Nov 26, 2022
🎉 基于 vite 2.0 + vue 3.0 + vue-router 4.0 + vuex 4.0 + element-plus 的后台管理系统vue3-element-admin

vue3-element-admin ?? 基于 Vite 2.0 + Vue3.0 + Vue-Router 4.0 + Vuex 4.0 + element-plus 的后台管理系统 简介 vue3-element-admin 是一个后台前端解决方案,它基于 vue3 和 element-plu

雪月欧巴 84 Nov 28, 2022
Vite template with TypeScript, Chakra UI, Eslint Airbnb, Prettier

Vite + Typescript + ChakraUI = ❤️ This is a vite template that combines several technologies: Vite React TypeScript ChakraUI Eslint with eslint-config

Lorenzo Rapetti 3 Mar 26, 2022
⏳ vue3 + electron + ts + vite = mini template

v3-electron ?? Electron16 + Vue3 + Vite2 运行项目 # enter the project directory cd v3-electron # install dependency yarn # develop yarn dev # build exe

UNPany 8 Nov 11, 2022
Using Cypress with Vite, React, TypeScript, MSW and react-query

Vie + Cypress + MSW + react-query Demo Example of using Cypress with Vite, MSW and react-query. Uses the appReady pattern to signal to Cypress when th

Rob Caldecott 9 Jul 16, 2022
Fastify boilerplate with Vite & Vitest

Fastify boilerplate with Vite & Vitest Enhance your Fastify DX with the power of Vite & Vitest. Features ⚡ All the power of Vite (Next Generation Fron

Emmanuel Salomon 31 Dec 13, 2022
Some compile-time magic for your Vite project

?? You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. vite-plugin-compile-time Use this plugin to generate

EGOIST 90 Dec 15, 2022
vite+vue3.2+setup+elementPlus+eslint+js+stylelint

前期准备工作,npm包和vscode配置 !!!很重要,关乎整个Vue3开发阶段的代码提示 Volar使用 使用Vue3开发需要禁用vscode插件Vetur 然后安装 Volar(Vue Language Features),这样Vue3代码提示即使是使用js开发也非常友好 如果volar没有任何

null 2 Feb 8, 2022
vue3 + vite + typescript template

Vue 3 + Typescript + Vite This template should help get you started developing with Vue 3 and Typescript in Vite. The template uses Vue 3 <script setu

BrowLi 6 Aug 1, 2022
Minimal setup for a WebXR project using Vite, Babylon.js, TypeScript, and Vue

WebXR-Vite-Babylon-Simple Minimal setup for WebXR development using: vite typescript vue 3 babylonjs 5 (ES6) Intentionally made minimal changes from t

Josh Sanderson 6 Nov 13, 2022
Modern ThreeJS boilerplate powered by Vite & Typescript

Modern ThreeJS ⚡️ Modern ThreeJS boilerplate powered by Vite & Typescript. Features Powered with Vite ?? GUI controls using Tweakpane ?? Typescript ??

Alvaro Saburido 64 Jan 4, 2023
Experimenting with vite typescript template rewrite for hot.opensauced.pizza

?? Open Sauced Vite Typescript Template Test ?? The path to your next Open Source contribution ?? Prerequisites In order to run the project we need th

TED Vortex (Teodor-Eugen Duțulescu) 3 Mar 11, 2022
⭐️ Auto create alias map for vite config

vite-plugin-tspaths2alias This plugin is create alias map for vite config, default use project root tsconfig.json file compilerOptions.paths value Ins

yankit 2 Mar 26, 2022
Get Vite's `import.meta.hot` at runtime

vite-hot-client Get Vite's import.meta.hot at runtime. You don't normally need this library directly. It's designed for embedded UI on top of Vite for

Anthony Fu 29 May 3, 2022
The design experiment for import.meta.glob from Vite.

vite-plugin-glob The design experiment for import.meta.glob from Vite. Motivations There are quite some scenarios that import.meta.glob wasn't conside

Anthony Fu 166 Sep 17, 2022
Integrate Vite and Electron

vite-plugin-electron Integrate Vite and Electron Example ?? vite-plugin-electron-quick-start Usage vite.config.ts import electron from 'vite-plugin-el

null 217 Jan 2, 2023