or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-url-loader

A webpack loader that transforms files into base64 URIs for efficient bundling

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/url-loader@4.1.x

To install, run

npx @tessl/cli install tessl/npm-url-loader@4.1.0

0

# URL Loader

1

2

URL Loader is a webpack loader that transforms files into base64 URIs for efficient bundling and deployment. It works as an intelligent alternative to file-loader by converting small files directly into data URLs while falling back to file-loader for larger files that exceed a configurable size limit.

3

4

## Package Information

5

6

- **Package Name**: url-loader

7

- **Package Type**: npm

8

- **Language**: JavaScript (Node.js)

9

- **Installation**: `npm install url-loader`

10

- **Webpack Versions**: 4.x and 5.x

11

- **Node.js**: >= 10.13.0

12

13

## Core Imports

14

15

For webpack configuration:

16

17

```javascript

18

// webpack.config.js

19

module.exports = {

20

module: {

21

rules: [

22

{

23

test: /\.(png|jpg|gif|svg)$/i,

24

use: [

25

{

26

loader: 'url-loader',

27

options: {

28

limit: 8192,

29

},

30

},

31

],

32

},

33

],

34

},

35

};

36

```

37

38

For programmatic usage (rare):

39

40

```javascript

41

const urlLoader = require('url-loader');

42

```

43

44

## Basic Usage

45

46

URL Loader is primarily used through webpack configuration. It automatically processes matched files during the webpack build process:

47

48

```javascript

49

// webpack.config.js

50

module.exports = {

51

module: {

52

rules: [

53

{

54

test: /\.(png|jpg|gif)$/i,

55

use: [

56

{

57

loader: 'url-loader',

58

options: {

59

limit: false, // Always use base64

60

},

61

},

62

],

63

},

64

{

65

test: /\.svg$/i,

66

use: [

67

{

68

loader: 'url-loader',

69

options: {

70

limit: 8192, // 8KB threshold

71

mimetype: 'image/svg+xml',

72

encoding: 'base64',

73

},

74

},

75

],

76

},

77

],

78

},

79

};

80

```

81

82

Application code using processed assets:

83

84

```javascript

85

import logoImage from './assets/logo.png'; // Will be base64 data URI if under limit

86

import iconSvg from './assets/icon.svg'; // Will be base64 data URI if under limit

87

88

// logoImage and iconSvg contain either:

89

// - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA... (if under limit)

90

// - /static/media/logo.abc123.png (if over limit, handled by fallback)

91

```

92

93

## Architecture

94

95

URL Loader operates as a webpack loader with the following key components:

96

97

- **Main Loader Function**: Processes file content and determines transformation strategy

98

- **Size-based Decision Logic**: Compares file size against configurable limit

99

- **Data URI Generation**: Converts files to base64 or other encoding formats

100

- **Fallback System**: Delegates to another loader (typically file-loader) for large files

101

- **Configuration Validation**: Validates all options against JSON schema

102

103

## Capabilities

104

105

### Main Loader Function

106

107

The primary webpack loader function that processes file content.

108

109

```javascript { .api }

110

/**

111

* Main webpack loader function - called by webpack during build

112

* @param {Buffer|string} content - File content to process

113

* @returns {string} JavaScript module code containing the data URI or fallback result

114

*/

115

function loader(content) {}

116

117

// Raw mode flag - indicates loader should receive Buffer instead of string

118

loader.raw = true;

119

```

120

121

### Configuration Options

122

123

Complete configuration interface for the loader options.

124

125

```javascript { .api }

126

interface LoaderOptions {

127

/** Maximum file size for base64 transformation */

128

limit?: boolean | number | string;

129

/** Encoding method for data URI generation */

130

encoding?: boolean | "utf8" | "utf16le" | "latin1" | "base64" | "hex" | "ascii" | "binary" | "ucs2";

131

/** MIME type for the generated data URI */

132

mimetype?: boolean | string;

133

/** Custom data URI generator function */

134

generator?: (content: Buffer, mimetype: string, encoding: string, resourcePath: string) => string;

135

/** Alternative loader for files exceeding the limit */

136

fallback?: string | FallbackConfig;

137

/** Generate ES module syntax instead of CommonJS */

138

esModule?: boolean;

139

}

140

141

interface FallbackConfig {

142

/** Fallback loader name */

143

loader: string;

144

/** Options to pass to fallback loader */

145

options?: object | string;

146

}

147

```

148

149

### Limit Configuration

150

151

Controls when files are transformed to base64 vs delegated to fallback loader.

152

153

```javascript { .api }

154

// Boolean mode

155

limit: true // Always transform to base64

156

limit: false // Never transform, always use fallback

157

158

// Numeric mode (bytes)

159

limit: 8192 // Transform files <= 8KB

160

limit: "10kb" // Transform files <= 10KB (string format)

161

```

162

163

**Usage Examples:**

164

165

```javascript

166

// Always convert to base64 (no size limit)

167

{

168

loader: 'url-loader',

169

options: {

170

limit: true

171

}

172

}

173

174

// Never convert to base64 (always use fallback)

175

{

176

loader: 'url-loader',

177

options: {

178

limit: false

179

}

180

}

181

182

// Size-based conversion (8KB threshold)

183

{

184

loader: 'url-loader',

185

options: {

186

limit: 8192

187

}

188

}

189

```

190

191

### MIME Type Configuration

192

193

Controls the MIME type included in generated data URIs.

194

195

```javascript { .api }

196

// Boolean mode

197

mimetype: true // Auto-detect from file extension

198

mimetype: false // Omit MIME type from data URI

199

200

// String mode

201

mimetype: "image/png" // Use specific MIME type

202

```

203

204

**Usage Examples:**

205

206

```javascript

207

// Auto-detect MIME type

208

{

209

loader: 'url-loader',

210

options: {

211

mimetype: true // Uses mime-types library

212

}

213

}

214

215

// Specific MIME type

216

{

217

loader: 'url-loader',

218

options: {

219

mimetype: 'image/svg+xml'

220

}

221

}

222

223

// No MIME type in data URI

224

{

225

loader: 'url-loader',

226

options: {

227

mimetype: false

228

}

229

}

230

```

231

232

### Encoding Configuration

233

234

Specifies how file content is encoded in the data URI.

235

236

```javascript { .api }

237

// Boolean mode

238

encoding: true // Use base64 encoding

239

encoding: false // No encoding (raw content)

240

241

// String mode - Node.js buffer encodings

242

encoding: "base64" | "utf8" | "utf16le" | "latin1" | "hex" | "ascii" | "binary" | "ucs2"

243

```

244

245

**Usage Examples:**

246

247

```javascript

248

// Base64 encoding (default)

249

{

250

loader: 'url-loader',

251

options: {

252

encoding: 'base64'

253

}

254

}

255

256

// UTF-8 encoding for text files

257

{

258

loader: 'url-loader',

259

options: {

260

encoding: 'utf8'

261

}

262

}

263

264

// No encoding

265

{

266

loader: 'url-loader',

267

options: {

268

encoding: false

269

}

270

}

271

```

272

273

### Custom Generator Function

274

275

Allows custom data URI generation logic.

276

277

```javascript { .api }

278

/**

279

* Custom generator function for creating data URIs

280

* @param {Buffer} content - File content as Buffer

281

* @param {string} mimetype - Resolved MIME type

282

* @param {string} encoding - Resolved encoding method

283

* @param {string} resourcePath - Full file path

284

* @returns {string} Custom data URI string

285

*/

286

type GeneratorFunction = (

287

content: Buffer,

288

mimetype: string,

289

encoding: string,

290

resourcePath: string

291

) => string;

292

```

293

294

**Usage Examples:**

295

296

```javascript

297

{

298

loader: 'url-loader',

299

options: {

300

generator: (content, mimetype, encoding, resourcePath) => {

301

// Custom logic for HTML files

302

if (/\.html$/i.test(resourcePath)) {

303

return `data:${mimetype},${content.toString()}`;

304

}

305

306

// Default behavior for other files

307

return `data:${mimetype}${encoding ? `;${encoding}` : ''},${content.toString(encoding)}`;

308

}

309

}

310

}

311

```

312

313

### Fallback Loader Configuration

314

315

Configures alternative loader for files exceeding the size limit.

316

317

```javascript { .api }

318

// String format

319

fallback: "file-loader"

320

fallback: "responsive-loader"

321

322

// Object format with options

323

fallback: {

324

loader: "file-loader",

325

options: {

326

name: "[name].[hash:8].[ext]",

327

outputPath: "images/"

328

}

329

}

330

```

331

332

**Usage Examples:**

333

334

```javascript

335

// Simple fallback

336

{

337

loader: 'url-loader',

338

options: {

339

limit: 8192,

340

fallback: 'file-loader'

341

}

342

}

343

344

// Fallback with custom options

345

{

346

loader: 'url-loader',

347

options: {

348

limit: 8192,

349

fallback: {

350

loader: 'file-loader',

351

options: {

352

name: '[path][name].[ext]',

353

outputPath: 'assets/'

354

}

355

}

356

}

357

}

358

359

// Advanced fallback

360

{

361

loader: 'url-loader',

362

options: {

363

limit: 8192,

364

fallback: require.resolve('responsive-loader'),

365

quality: 85 // This option passes through to responsive-loader

366

}

367

}

368

```

369

370

### ES Module Configuration

371

372

Controls output module format.

373

374

```javascript { .api }

375

esModule: boolean // Default: true

376

```

377

378

**Usage Examples:**

379

380

```javascript

381

// ES module output (default)

382

{

383

loader: 'url-loader',

384

options: {

385

esModule: true

386

}

387

}

388

// Generates: export default "data:image/png;base64,..."

389

390

// CommonJS output

391

{

392

loader: 'url-loader',

393

options: {

394

esModule: false

395

}

396

}

397

// Generates: module.exports = "data:image/png;base64,..."

398

```

399

400

## Error Handling

401

402

URL Loader validates all options and throws errors for:

403

404

- **Invalid Options**: Schema validation failures for malformed configuration

405

- **Missing Fallback**: When fallback loader cannot be resolved or loaded

406

- **Encoding Errors**: When specified encoding is not supported by Node.js

407

- **File System Errors**: When file cannot be read during processing

408

409

Common error scenarios:

410

411

```javascript

412

// Invalid limit type

413

{

414

loader: 'url-loader',

415

options: {

416

limit: {} // Error: limit must be boolean, number, or string

417

}

418

}

419

420

// Invalid encoding

421

{

422

loader: 'url-loader',

423

options: {

424

encoding: 'invalid' // Error: unsupported encoding

425

}

426

}

427

428

// Missing fallback loader

429

{

430

loader: 'url-loader',

431

options: {

432

fallback: 'nonexistent-loader' // Error: cannot resolve loader

433

}

434

}

435

```

436

437

## Dependencies

438

439

### Required Dependencies

440

441

- **loader-utils** (^2.0.0): Webpack loader utilities for option parsing

442

- **mime-types** (^2.1.27): MIME type detection from file extensions

443

- **schema-utils** (^3.0.0): JSON schema validation for loader options

444

445

### Peer Dependencies

446

447

- **webpack** (^4.0.0 || ^5.0.0): Required webpack version

448

- **file-loader** (*): Optional, used as default fallback loader

449

450

### Runtime Requirements

451

452

- **Node.js**: >= 10.13.0

453

- **Environment**: Node.js server-side (webpack build process)

454

455

## CommonJS and ES Module Support

456

457

URL Loader provides both CommonJS and ES module interfaces:

458

459

```javascript { .api }

460

// CommonJS (main entry - dist/cjs.js)

461

const urlLoader = require('url-loader');

462

urlLoader.raw; // true

463

464

// ES Module (source - src/index.js)

465

import urlLoader, { raw } from 'url-loader/src';

466

```

467

468

Note: The ES module version is the source code and requires transpilation for older Node.js versions.