or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# @rollup/plugin-url

1

2

@rollup/plugin-url is a Rollup plugin that imports files as data-URIs or ES Modules. It automatically processes static assets like images, fonts, and other binary files by either inlining small files as data-URIs for performance optimization or copying larger files to the output directory with hashed filenames to prevent caching issues.

3

4

## Package Information

5

6

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

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript

9

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

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

For CommonJS:

18

19

```javascript

20

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

21

```

22

23

## Basic Usage

24

25

```javascript

26

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

27

28

export default {

29

input: 'src/index.js',

30

output: {

31

dir: 'output',

32

format: 'cjs'

33

},

34

plugins: [url()]

35

};

36

```

37

38

Import assets in your source code:

39

40

```javascript

41

// Import an image - returns either a data-URI or file path

42

import imageUrl from './assets/logo.png';

43

import iconSvg from './icons/home.svg';

44

45

console.log(`Image URL: ${imageUrl}`);

46

```

47

48

## Capabilities

49

50

### Plugin Factory Function

51

52

Creates a Rollup plugin instance for processing file imports as data-URIs or ES modules.

53

54

```javascript { .api }

55

/**

56

* Creates a Rollup plugin for importing files as data-URIs or ES Modules

57

* @param options - Configuration options for the plugin

58

* @returns Rollup plugin object

59

*/

60

function url(options?: RollupUrlOptions): Plugin;

61

62

interface RollupUrlOptions {

63

/**

64

* File patterns to include in processing

65

* @default ['**/*.svg', '**/*.png', '**/*.jp(e)?g', '**/*.gif', '**/*.webp']

66

*/

67

include?: FilterPattern;

68

/**

69

* File patterns to exclude from processing

70

* @default undefined

71

*/

72

exclude?: FilterPattern;

73

/**

74

* File size limit in bytes for inlining

75

* Files larger than this will be copied instead of inlined

76

* Set to 0 to copy all files

77

* @default 14336 (14kb)

78

*/

79

limit?: number;

80

/**

81

* String prefix for non-inlined file paths

82

* @default ''

83

*/

84

publicPath?: string;

85

/**

86

* Whether to emit files to output directory

87

* Set to false for server-side builds

88

* @default true

89

*/

90

emitFiles?: boolean;

91

/**

92

* Template for output filenames

93

* Supports [hash], [name], [extname], [dirname] placeholders

94

* @default '[hash][extname]'

95

*/

96

fileName?: string;

97

/**

98

* Source directory for [dirname] replacement

99

* @default ''

100

*/

101

sourceDir?: string;

102

/**

103

* Destination directory for copied assets

104

* @default ''

105

*/

106

destDir?: string;

107

}

108

109

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

110

111

interface Plugin {

112

name: string;

113

load(id: string): Promise<string | null>;

114

generateBundle(outputOptions: any): Promise<void>;

115

}

116

```

117

118

**Basic Configuration:**

119

120

```javascript

121

export default {

122

plugins: [

123

url({

124

limit: 8192, // 8kb limit

125

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

126

publicPath: '/assets/'

127

})

128

]

129

};

130

```

131

132

**Advanced Configuration:**

133

134

```javascript

135

import path from 'path';

136

137

export default {

138

plugins: [

139

url({

140

limit: 0, // Copy all files (no inlining)

141

fileName: '[dirname][name].[hash][extname]',

142

sourceDir: path.join(__dirname, 'src'),

143

destDir: 'dist/assets',

144

publicPath: 'https://cdn.example.com/assets/'

145

})

146

]

147

};

148

```

149

150

**Server-side Rendering:**

151

152

```javascript

153

export default {

154

plugins: [

155

url({

156

emitFiles: false, // Prevent file emission for SSR builds

157

publicPath: '/static/'

158

})

159

]

160

};

161

```

162

163

### File Processing Logic

164

165

The plugin processes files based on size and configuration:

166

167

1. **File Filtering**: Uses include/exclude patterns to determine which files to process

168

2. **Size Check**: Compares file size against the limit option

169

3. **Small Files (≤ limit)**: Converted to data-URIs

170

- Images: Base64-encoded data-URIs (`data:image/png;base64,iVBOR...`)

171

- SVG: URI-encoded data-URIs (`data:image/svg+xml,<encoded-svg>`)

172

- SVG files undergo special processing: newlines/tabs removed, comments stripped, single quotes escaped

173

- Brackets and parentheses are percent-encoded for URL safety

174

4. **Large Files (> limit)**: Copied to output directory

175

- Filename generated using template with hash for cache-busting

176

- Returns file path prefixed with publicPath

177

178

### Filename Template Placeholders

179

180

When `emitFiles` is true and files exceed the size limit, the `fileName` template supports these placeholders:

181

182

- `[hash]`: SHA-1 hash of file contents (first 16 characters)

183

- `[name]`: Original filename without extension

184

- `[extname]`: File extension including the leading dot

185

- `[dirname]`: Parent directory name or relative path from sourceDir

186

187

**Template Examples:**

188

189

```javascript

190

// Default: '[hash][extname]'

191

// logo.png → 'a1b2c3d4e5f6g7h8.png'

192

193

// '[name].[hash][extname]'

194

// logo.png → 'logo.a1b2c3d4e5f6g7h8.png'

195

196

// '[dirname][hash][extname]'

197

// assets/logo.png → 'assets/a1b2c3d4e5f6g7h8.png'

198

```

199

200

### Supported File Types

201

202

By default, these file types are processed:

203

204

- **SVG**: Vector graphics (`**/*.svg`)

205

- **PNG**: Raster images (`**/*.png`)

206

- **JPEG**: Raster images (`**/*.jp(e)?g`)

207

- **GIF**: Animated images (`**/*.gif`)

208

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

209

210

**Custom File Types:**

211

212

```javascript

213

export default {

214

plugins: [

215

url({

216

include: [

217

'**/*.svg', '**/*.png', '**/*.jpg', '**/*.gif', '**/*.webp',

218

'**/*.woff', '**/*.woff2', '**/*.eot', '**/*.ttf' // Add fonts

219

]

220

})

221

]

222

};

223

```

224

225

### Error Handling

226

227

The plugin handles common error scenarios:

228

229

- **File not found**: Returns null from the `load` hook, letting Rollup handle the error

230

- **File system errors**: Read/stat failures from `fs.readFile` and `fs.stat` are propagated as build errors

231

- **Directory creation failures**: Errors from `makeDir` during file emission are propagated

232

- **Copy operation failures**: Stream errors during file copying (from `fs.createReadStream`/`fs.createWriteStream`) are propagated

233

- **Invalid options**: Plugin uses default values for undefined options, applies filtering via `@rollup/pluginutils`

234

235

### Integration Examples

236

237

**With TypeScript:**

238

239

```typescript

240

// rollup.config.ts

241

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

242

import type { RollupOptions } from 'rollup';

243

244

const config: RollupOptions = {

245

plugins: [

246

url({

247

limit: 10240,

248

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

249

publicPath: '/static/'

250

})

251

]

252

};

253

254

export default config;

255

```

256

257

**With Vite (Rollup-based):**

258

259

```javascript

260

// vite.config.js

261

import { defineConfig } from 'vite';

262

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

263

264

export default defineConfig({

265

build: {

266

rollupOptions: {

267

plugins: [

268

url({

269

limit: 8192,

270

publicPath: '/assets/'

271

})

272

]

273

}

274

}

275

});

276

```

277

278

**Multiple Build Targets:**

279

280

```javascript

281

// rollup.config.js

282

export default [

283

// Client build

284

{

285

input: 'src/client.js',

286

plugins: [url({ emitFiles: true, publicPath: '/assets/' })]

287

},

288

// Server build

289

{

290

input: 'src/server.js',

291

plugins: [url({ emitFiles: false, publicPath: '/assets/' })]

292

}

293

];

294

```