note: If you are reading this on npm, please note that this README is only updated per release. Sometimes deficiencies in the README are fixed in master but not yet published so make sure to check the github (and open an issue :D) page if something here is incorrect!
When building an application using server-side rendering, the need to calculate aspect ratios from image or video files in order to prevent layout jank often arises. While looking for alternatives โ as to not have to write this myself โ I stumbled upon some other packages:
These seem to primarily concern themselves with outputting a prefixed
path based off of the import statement, however. This does not include getting
the width, height, or aspectRatio of a given image / video.
This plugin attempts to solve these issues by providing a simple way to
get what you need without having to jump through many hoops / module bundlers.
Transforms the following:
import avatar from 'avatar.jpg';Into:
var avatar = {
pathname: '/avatar.jpg',
src: '/avatar.jpg',
width: 280,
height: 280,
aspectRatio: 1,
heightToWidthRatio: 1,
type: 'jpg'
};- babel-plugin-transform-media-imports
- Table of Contents
- Changelog
- Node support
- Installation
- Usage
- Configuration
dates are listed in dd-mm-yyyy format
- Update dependencies
- Update dependencies
- Test node 18
- Add package description
- Update dependencies
- Update dependencies
- Update dependencies
- Replace
image-sizewithleather, removing the need forffprobe๐
- Update dependencies, add node 16.5 to travis.yml
- Update dependencies (should have been a patch update, woops!)
- Add
mkdirpdependency, back to 2 deps :/ - Fix issues with creating directories recursively in older (< 10.0.0) node versions
- Add ability to output files with outputRoot.
- Remove
md5-filedependency, it's only 1 dep now ๐ฅ. - Make
.svgfile content available through acontentproperty. - Rename
md5option tohash,md5now gets aliassed tohashfor backwards compat.- Add
algooption to specify a valid node crypto hash algorithm.
- Add
- Added meta information
This plugin is tested in the following NodeJS versions:
- Node.js 16.5.0
- Node.js 15.0.0
- Node.js 14.0.0
- Node.js 13.0.0
- Node.js 12.0.0
The plugin itself may work in older versions such as node 9 or maybe even 8 but mocha requires at least node version 10.13 for running tests.
Add this plugin to your package / application with:
npm:
npm install -S babel-plugin-transform-media-importsyarn:
yarn add babel-plugin-transform-media-importsAfterwards, add the plugin to your .babelrc plugins:
{
"plugins": ["transform-media-imports"]
}After following the installation steps above, you can now directly import
images and videos into your JS files. This will result in an object with some useful properties:
pathnamethe path of the file with baseDir removed and pathnamePrefix prepended.srcthe same aspathnameunless base64 was specified and the file size was less thanbase64.maxSize.hashwhen hash is enabled, this property contains the generated hash,undefinedotherwise.typetype of the media file, e.g.'jpg','svg','mp4'widthwidth in pixels of the media fileheightheight in pixels of the media filecontentif the file is ansvg, thecontentproperty will contain the raw svg file contents.aspectRatiocalculated aspect ratio usingwidth / heightrounded to 3 decimal places.heightToWidthRatiocalculated ratio usingheight / widthrounded to 3 decimal places.
(useful for ::after padding aspect ratio hack)
To import an image including all its properties:
import image from 'path/to/image.jpg';Which will be transformed into:
var image = {
pathname: 'path/to/image.jpg',
src: 'path/to/image.jpg',
width: 1234,
height: 1234,
aspectRatio: 1,
heightToWidthRatio: 1,
type: 'jpg'
};To export an image including all its properties:
export {default as image} from 'path/to/image.jpg';When using @babel/plugin-proposal-export-default-from, a default export can be used instead:
export image from 'path/to/image.jpg';Either will be transformed into:
const _image = {
pathname: 'path/to/image.jpg',
src: 'path/to/image.jpg',
width: 1234,
height: 1234,
aspectRatio: 1,
heightToWidthRatio: 1,
type: 'jpg'
};
export { _image as image };If you only need to import a specific property, members may be imported using named imports:
import {width, height, heightToWidthRatio} from 'path/to/image.jpg';Which will be transformed into:
const width = 1234;
const height = 1234;
const heightToWidthRatio = 1;If you only need to export a specific property, members may be exported using named exports:
export {width, height, heightToWidthRatio} from 'path/to/image.jpg';Which will be transformed into:
export const width = 1234;
export const height = 1234;
export const heightToWidthRatio = 1;This is the default configuration of the plugin, each option is detailed below:
[
'transform-media-imports',
{
baseDir: process.cwd(),
pathnamePrefix: '',
outputRoot: null,
imageExtensions: ['jpeg', 'apng', 'jpg', 'png', 'gif', 'svg', 'bmp', 'cur', 'ico', 'psd', 'dds'],
videoExtensions: ['mp4', 'webm', 'ogv'],
hash: false,
base64: false
}
]default: process.cwd()
Everything before this path gets removed from the src and pathname attributes.
default: ''
After removing the baseDir, the pathnamePrefix gets prepended to
the src and pathname attributes.
default: null
When specified, writes output file(s) to outputRoot/{pathname} where pathname
is the specified media file's pathname attribute.
default: ['jpeg', 'apng', 'jpg', 'png', 'gif', 'svg', 'bmp', 'cur', 'ico', 'psd', 'dds']
Specify supported image extensions that will be transformed.
By default, all extensions that leather
supports are added to the list in addition to prepending 'jpeg' and 'apng' to allow
for regex matching of files using that extension as well.
default: ['mp4', 'webm', 'ogv']
Specify supported video extensions that will be transformed.
formerly named md5, the old name is still supported and will work the same way
default: null
When set to true, adds a hash to the src and pathname attributes:
import {pathname} from 'avatar.jpg';Transforms into:
const pathname = 'avatar-3h2jk5gjkh35guighjg3hj5ghdjkahd34kj.jpg'When set to an object, adds an md5 hash configured by it. The following properties are configurable:
{
length: 10, // trims md5 length to first <N> characters
delimiter: '.', // delimiter to join filename and md5: [filename][delimiter][md5].[ext]
algo: 'md5' // a valid node 'crypto' createHash algorithm such as md5 or sha256, defaults to md5
}After applying the above configuration the import looks like this:
const pathname = 'avatar.3h2jk5gjkh.jpg'default: null
When set to true, sets the src attribute to the base64 string including
web mime type when the file is <= 8192 bytes:
import {src} from 'avatar.jpg';Transforms into:
var src = 'data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QCCRXhp...'When set to an object, the maxSize of 8192 may be overridden:
{
maxSize: 10000 // allow files up to 10kb to be transformed to base64
}