or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# @rollup/plugin-image

1

2

A Rollup plugin that imports JPG, PNG, GIF, SVG, and WebP files directly into JavaScript modules. The plugin converts images to base64-encoded strings or DOM Image elements, making them immediately available at startup without requiring asynchronous loading.

3

4

Images are encoded using base64, which means they will be 33% larger than the size on disk. This plugin is ideal for small images where the convenience of immediate availability outweighs the 33% size increase, such as icons, logos, or UI elements that need to be available synchronously.

5

6

## Package Information

7

8

- **Package Name**: @rollup/plugin-image

9

- **Package Type**: npm

10

- **Language**: JavaScript/TypeScript

11

- **Installation**: `npm install @rollup/plugin-image --save-dev`

12

- **Requirements**: Node.js v14.0.0+ and Rollup v1.20.0+

13

14

## Core Imports

15

16

```javascript

17

import image from '@rollup/plugin-image';

18

```

19

20

For CommonJS:

21

22

```javascript

23

const image = require('@rollup/plugin-image');

24

```

25

26

## Basic Usage

27

28

### Plugin Configuration

29

30

```javascript

31

// rollup.config.js

32

import image from '@rollup/plugin-image';

33

34

export default {

35

input: 'src/index.js',

36

output: {

37

dir: 'output',

38

format: 'cjs'

39

},

40

plugins: [image()]

41

};

42

```

43

44

### Importing Images (Base64 Mode - Default)

45

46

```javascript

47

// src/index.js

48

import logo from './rollup.png';

49

50

console.log(logo); // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."

51

```

52

53

### Importing Images (DOM Mode)

54

55

```javascript

56

// rollup.config.js with DOM mode enabled

57

import image from '@rollup/plugin-image';

58

59

export default {

60

input: 'src/index.js',

61

output: { dir: 'output', format: 'cjs' },

62

plugins: [image({ dom: true })]

63

};

64

```

65

66

```javascript

67

// src/index.js

68

import logo from './rollup.png';

69

70

document.body.appendChild(logo); // logo is now a DOM Image element

71

```

72

73

## Capabilities

74

75

### Plugin Factory Function

76

77

Creates a Rollup plugin instance that processes image files.

78

79

```javascript { .api }

80

/**

81

* Creates a Rollup plugin for importing image files as base64 strings or DOM elements

82

* @param options - Configuration options for the plugin

83

* @returns Rollup plugin object

84

*/

85

function image(options?: RollupImageOptions): Plugin;

86

```

87

88

### Configuration Options

89

90

```typescript { .api }

91

interface RollupImageOptions {

92

/**

93

* A picomatch pattern, or array of patterns, which specifies the files

94

* the plugin should operate on. By default all files are targeted.

95

*/

96

include?: FilterPattern;

97

98

/**

99

* A picomatch pattern, or array of patterns, which specifies the files

100

* the plugin should ignore. By default no files are ignored.

101

*/

102

exclude?: FilterPattern;

103

104

/**

105

* If true, generates DOM Image elements instead of base64 strings.

106

* If false (default), generates base64 data URI strings.

107

* @default false

108

*/

109

dom?: boolean;

110

}

111

```

112

113

**Usage Examples:**

114

115

```javascript

116

// Basic usage - processes all image files

117

export default {

118

plugins: [image()]

119

};

120

121

// Filter specific files

122

export default {

123

plugins: [image({

124

include: ['**/*.png', '**/*.jpg'],

125

exclude: ['**/test-images/**']

126

})]

127

};

128

129

// DOM mode for browser usage

130

export default {

131

plugins: [image({ dom: true })]

132

};

133

```

134

135

### Plugin Object

136

137

The plugin returns a standard Rollup plugin object with the following structure:

138

139

```javascript { .api }

140

interface Plugin {

141

/** Plugin identifier */

142

name: 'image';

143

144

/**

145

* Load hook that processes image files and returns transformed code

146

* @param id - File path being loaded

147

* @returns Transformed JavaScript code or null if file should be ignored

148

*/

149

load(id: string): string | null;

150

151

/**

152

* Adds a file to Rollup's watch list (called internally by load hook)

153

* @param id - File path to watch for changes

154

*/

155

addWatchFile?(id: string): void;

156

}

157

```

158

159

## Supported File Types

160

161

The plugin processes files with the following extensions and MIME types:

162

163

- **JPG/JPEG** (`image/jpeg`): `.jpg`, `.jpeg`

164

- **PNG** (`image/png`): `.png`

165

- **GIF** (`image/gif`): `.gif`

166

- **SVG** (`image/svg+xml`): `.svg`

167

- **WebP** (`image/webp`): `.webp`

168

169

## Export Modes

170

171

### Base64 Mode (Default)

172

173

When `dom: false` (default), imported images are exported as base64-encoded data URI strings:

174

175

```javascript

176

import logo from './image.png';

177

// logo is a string: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."

178

179

// Can be used in CSS, HTML, or canvas contexts

180

const img = new Image();

181

img.src = logo;

182

```

183

184

### DOM Mode

185

186

When `dom: true`, imported images are exported as ready-to-use DOM Image elements:

187

188

```javascript

189

import logo from './image.png';

190

// logo is an Image object that can be directly appended to DOM

191

192

document.body.appendChild(logo);

193

// or

194

canvas.getContext('2d').drawImage(logo, 0, 0);

195

```

196

197

## Types

198

199

### Core Types

200

201

```typescript { .api }

202

import type { FilterPattern } from '@rollup/pluginutils';

203

import type { Plugin } from 'rollup';

204

205

type FilterPattern = string | RegExp | Array<string | RegExp> | null;

206

```

207

208

### Dependencies

209

210

- **@rollup/pluginutils**: Provides `createFilter()` utility and `FilterPattern` type

211

- **mini-svg-data-uri**: Optimizes SVG data URI encoding for smaller output

212

- **Node.js built-ins**: `fs.readFileSync()` for file reading, `path.extname()` for extension detection

213

214

## Error Handling

215

216

The plugin handles various error conditions during the build process:

217

218

### File Processing Errors

219

220

- **Non-image files**: Files that don't match supported extensions (`.jpg`, `.jpeg`, `.png`, `.gif`, `.svg`, `.webp`) are ignored (plugin returns `null`)

221

- **Filtered files**: Files that don't pass the include/exclude filter are ignored (plugin returns `null`)

222

- **Missing files**: If an imported image file doesn't exist, Rollup will throw a build error with the message "Could not load [file path]"

223

- **Corrupted files**: Invalid or corrupted image files will cause `fs.readFileSync()` to throw system errors, failing the build

224

225

### Common Error Messages

226

227

```

228

Error: Could not load ./path/to/image.png (imported by src/index.js)

229

```

230

This occurs when the image file doesn't exist at the specified path.

231

232

```

233

ENOENT: no such file or directory, open './path/to/image.png'

234

```

235

System error when the file cannot be read from disk.

236

237

### Error Prevention

238

239

- Ensure all imported image files exist in the correct relative paths

240

- Use appropriate include/exclude patterns to avoid processing non-image files

241

- Verify file permissions allow reading by the build process

242

243

## Performance Considerations

244

245

- **Size Impact**: Base64 encoding increases file size by approximately 33%

246

- **Memory Usage**: All images are loaded into memory during build time

247

- **Build Performance**: Large images or many images can slow down the build process

248

- **Runtime Performance**: Images are immediately available without network requests

249

- **Best Practice**: Use for small images (icons, logos) rather than large photos or assets