or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-imagemin

Minify images seamlessly with support for multiple formats and plugin-based optimization

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/imagemin@9.0.x

To install, run

npx @tessl/cli install tessl/npm-imagemin@9.0.0

0

# imagemin

1

2

imagemin is a Node.js library that provides seamless image minification through a plugin-based architecture. It supports multiple image formats (JPEG, PNG, GIF, SVG, WebP) and offers both file-based and buffer-based processing with glob pattern support for batch operations.

3

4

## Package Information

5

6

- **Package Name**: imagemin

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES Modules)

9

- **Installation**: `npm install imagemin`

10

11

## Core Imports

12

13

```javascript

14

import imagemin from 'imagemin';

15

```

16

17

Note: This package only supports ES modules and requires Node.js 18+. CommonJS import is not supported.

18

19

## Basic Usage

20

21

```javascript

22

import imagemin from 'imagemin';

23

import imageminJpegtran from 'imagemin-jpegtran';

24

import imageminPngquant from 'imagemin-pngquant';

25

26

// Process image files with plugins

27

const files = await imagemin(['images/*.{jpg,png}'], {

28

destination: 'build/images',

29

plugins: [

30

imageminJpegtran(),

31

imageminPngquant({

32

quality: [0.6, 0.8]

33

})

34

]

35

});

36

37

console.log(files);

38

// Returns: [{data: Uint8Array, sourcePath: string, destinationPath: string}, ...]

39

40

// Process image buffer directly

41

import fs from 'node:fs/promises';

42

const buffer = await fs.readFile('image.jpg');

43

const optimizedBuffer = await imagemin.buffer(buffer, {

44

plugins: [imageminJpegtran()]

45

});

46

```

47

48

## Architecture

49

50

imagemin follows a plugin-based architecture with these key components:

51

52

- **Main Function**: Processes files or glob patterns, handles file I/O and directory creation

53

- **Buffer Processing**: Direct binary data processing without file system operations

54

- **Plugin System**: Chainable image optimization plugins using p-pipe for sequential processing

55

- **File Type Detection**: Automatic format detection and extension handling

56

- **Glob Support**: Pattern matching for batch file processing using globby

57

58

## Capabilities

59

60

### File-based Image Processing

61

62

The main imagemin function processes image files from the filesystem using glob patterns.

63

64

```javascript { .api }

65

/**

66

* Minify images from file paths or glob patterns

67

* @param {string[]} input - Array of file paths or glob patterns to process

68

* @param {Object} [options] - Processing options including destination and plugins

69

* @param {string} [options.destination] - Output directory path

70

* @param {Function[]} [options.plugins] - Array of imagemin plugins to apply

71

* @param {boolean} [options.glob=true] - Enable/disable glob pattern matching

72

* @returns {Promise<Array<Object>>} Promise resolving to array of processing results

73

*/

74

function imagemin(input, options);

75

```

76

77

**Parameters:**

78

- `input`: Array of file paths or glob patterns (e.g., `['images/*.jpg', 'photos/*.png']`)

79

- `options.destination`: Optional output directory. If not provided, files are not written to disk

80

- `options.plugins`: Array of imagemin plugins to apply sequentially

81

- `options.glob`: Enable/disable glob pattern matching (default: `true`)

82

83

**Returns:** Array of objects with the following properties:

84

- `data` (Uint8Array): Optimized image data

85

- `sourcePath` (string): Original file path

86

- `destinationPath` (string|undefined): Output file path (undefined if no destination specified)

87

88

**Usage Examples:**

89

90

```javascript

91

// Basic file processing without saving

92

const results = await imagemin(['src/images/*.jpg']);

93

94

// Process and save to destination

95

const files = await imagemin(['src/images/*.{jpg,png}'], {

96

destination: 'dist/images',

97

plugins: [imageminJpegtran(), imageminPngquant()]

98

});

99

100

// Disable glob patterns for exact file paths

101

const exactFiles = await imagemin(['photo1.jpg', 'photo2.png'], {

102

glob: false,

103

plugins: [imageminJpegtran()]

104

});

105

```

106

107

### Buffer-based Image Processing

108

109

Process image data directly from memory without filesystem operations.

110

111

```javascript { .api }

112

/**

113

* Minify image data from a buffer

114

* @param {Uint8Array} data - Image data as Uint8Array

115

* @param {Object} [options] - Processing options with plugins

116

* @param {Function[]} [options.plugins] - Array of imagemin plugins to apply

117

* @returns {Promise<Uint8Array>} Promise resolving to optimized image data

118

*/

119

imagemin.buffer(data, options);

120

```

121

122

**Parameters:**

123

- `data` (Uint8Array): Image data as Uint8Array (validated at runtime)

124

- `options.plugins` (Function[]): Array of imagemin plugins to apply sequentially

125

126

**Returns:** Optimized image data as Uint8Array

127

128

**Usage Examples:**

129

130

```javascript

131

import fs from 'node:fs/promises';

132

133

// Process buffer from file

134

const buffer = await fs.readFile('image.jpg');

135

const optimized = await imagemin.buffer(buffer, {

136

plugins: [imageminJpegtran()]

137

});

138

139

// Process buffer from HTTP response

140

const response = await fetch('https://example.com/image.jpg');

141

const imageBuffer = new Uint8Array(await response.arrayBuffer());

142

const result = await imagemin.buffer(imageBuffer, {

143

plugins: [imageminWebp()]

144

});

145

```

146

147

## Plugin System

148

149

imagemin uses a plugin-based architecture where plugins are functions that process image data. Plugins are applied sequentially using p-pipe.

150

151

### Plugin Interface

152

153

```javascript { .api }

154

/**

155

* Plugin function signature - all imagemin plugins follow this interface

156

* @param {Uint8Array|Buffer} buffer - Image data to process

157

* @returns {Promise<Uint8Array|Buffer>} Processed image data

158

*/

159

function imageminPlugin(buffer);

160

```

161

162

### Common Plugins

163

164

Popular imagemin plugins for different formats:

165

166

- **imagemin-jpegtran**: Lossless JPEG optimization

167

- **imagemin-mozjpeg**: Lossy JPEG compression with quality control

168

- **imagemin-pngquant**: PNG compression with quality settings

169

- **imagemin-optipng**: Lossless PNG optimization

170

- **imagemin-svgo**: SVG optimization and minification

171

- **imagemin-webp**: WebP conversion and optimization

172

- **imagemin-gif2webp**: GIF to WebP conversion

173

174

## Error Handling

175

176

imagemin throws errors in several scenarios:

177

178

- **Browser Environment**: Throws error when run in browser (not supported)

179

- **Invalid Input Types**: Validates input arrays and Uint8Array buffers

180

- **File Processing Errors**: Plugin-specific errors (e.g., corrupt image data)

181

- **File System Errors**: Directory creation or file write failures

182

183

**Error Examples:**

184

185

```javascript

186

// Browser environment error

187

if (typeof window !== 'undefined') {

188

// Throws: "This package does not work in the browser."

189

}

190

191

// Type validation errors

192

await imagemin('not-an-array'); // Throws type error

193

await imagemin.buffer('not-a-buffer'); // Throws Uint8Array validation error

194

195

// Plugin processing errors

196

try {

197

await imagemin(['corrupt-image.jpg'], {

198

plugins: [imageminJpegtran()]

199

});

200

} catch (error) {

201

console.log(error.message); // "Error occurred when handling file: ..."

202

}

203

```

204

205

## Special Behaviors

206

207

### File Extension Handling

208

209

imagemin automatically handles file extension changes based on output format:

210

211

- **WebP Conversion**: Automatically changes extension to `.webp` when using WebP plugins

212

- **Format Detection**: Uses file-type library to detect actual format from buffer data

213

- **Extension Fallback**: Falls back to original file extension if format detection fails

214

215

### Junk File Filtering

216

217

Automatically filters out system files:

218

- `.DS_Store` (macOS)

219

- `Thumbs.db` (Windows)

220

- Other junk files detected by the junk library

221

222

### Dimension Validation

223

224

Skips processing of images with invalid dimensions (0x0 pixels) to handle corrupted files gracefully.

225

226

### Path Handling

227

228

- **Unix Path Conversion**: Converts Windows path separators to Unix format internally

229

- **Glob Pattern Support**: Full globby pattern support including `**` for recursive matching

230

- **Directory Creation**: Automatically creates output directories as needed