or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-main-bower-files

Get main files from your installed bower packages.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/main-bower-files@2.13.x

To install, run

npx @tessl/cli install tessl/npm-main-bower-files@2.13.0

0

# main-bower-files

1

2

A utility library that extracts main files from installed Bower packages by reading bower.json configurations. It provides flexible filtering mechanisms and comprehensive integration with build systems like Gulp and Grunt, making it essential for front-end build processes that need to programmatically identify and process primary files from Bower dependencies.

3

4

## Package Information

5

6

- **Package Name**: main-bower-files

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install main-bower-files`

10

11

## Core Imports

12

13

```javascript

14

const mainBowerFiles = require('main-bower-files');

15

```

16

17

## Basic Usage

18

19

```javascript

20

const mainBowerFiles = require('main-bower-files');

21

22

// Get all main files from bower packages

23

const files = mainBowerFiles();

24

25

// Filter files with glob patterns

26

const jsFiles = mainBowerFiles('**/*.js');

27

28

// Use with options

29

const files = mainBowerFiles({

30

debugging: true,

31

checkExistence: true,

32

includeDev: true

33

});

34

35

// Async with callback

36

mainBowerFiles((err, files) => {

37

if (err) throw err;

38

console.log(files);

39

});

40

```

41

42

## Architecture

43

44

The main-bower-files package is built around several key internal components:

45

46

- **Main Module**: The primary export function with flexible parameter overloading

47

- **PackageCollection**: Manages the collection of bower packages and their dependencies

48

- **Package**: Represents individual bower packages with their metadata and file resolution

49

- **Logger**: Provides colored debug output for troubleshooting

50

- **Grunt Task**: Integrated Grunt multitask for build system workflows

51

52

The architecture follows a hierarchical pattern where the main function creates a PackageCollection, which manages multiple Package instances that handle individual bower package resolution and dependency tracking.

53

54

## Capabilities

55

56

### Main Module Export

57

58

The primary module export function that extracts main files from installed Bower packages with flexible parameter overloading.

59

60

```javascript { .api }

61

/**

62

* Main module export - extracts main files from installed Bower packages

63

* @param {string|Array<string>|RegExp|Function} [filter] - File filtering (glob patterns, regex, function, or array)

64

* @param {Options} [options] - Configuration options

65

* @param {Function} [callback] - Optional callback function (error, files) => void

66

* @returns {Array<string>} Array of absolute file paths from Bower packages

67

*/

68

module.exports = function(filter, options, callback) { ... };

69

```

70

71

#### Filter Parameter

72

73

The filter parameter supports multiple formats for file selection:

74

75

- **String**: Glob pattern (e.g., `'**/*.js'`, `'**/*.css'`)

76

- **Array**: Multiple glob patterns (e.g., `['**/*.js', '**/*.css']`)

77

- **RegExp**: Regular expression for file matching

78

- **Function**: Custom filter function `(filepath) => boolean`

79

80

#### Options Object

81

82

```javascript { .api }

83

/**

84

* Configuration options for main-bower-files

85

* @typedef {Object} Options

86

* @property {boolean} [debugging=false] - Enable debug output

87

* @property {string|Array<string>|Object} [main] - Default main property for packages without one

88

* @property {string} [env=process.env.NODE_ENV] - Environment for conditional main files

89

* @property {PathsConfig|string} [paths] - Custom paths configuration

90

* @property {boolean} [checkExistence=false] - Validate file existence

91

* @property {boolean|string} [includeDev=false] - Include devDependencies ('inclusive', 'exclusive', true, false)

92

* @property {boolean} [includeSelf=false] - Include current package main files

93

* @property {string|Array<string>|RegExp|Function} [filter] - File filtering

94

* @property {Object} [overrides={}] - Default package overrides

95

* @property {string|Array<string>} [group] - Select specific dependency groups

96

* @property {string} [base] - Base path for file resolution

97

*/

98

99

/**

100

* Path configuration options

101

* @typedef {Object} PathsConfig

102

* @property {string} [bowerDirectory] - Path to bower_components directory

103

* @property {string} [bowerrc] - Path to .bowerrc file

104

* @property {string} [bowerJson] - Path to bower.json file

105

*/

106

```

107

108

### Build System Integration

109

110

#### Gulp Integration

111

112

```javascript

113

const gulp = require('gulp');

114

const mainBowerFiles = require('main-bower-files');

115

116

gulp.task('bower', function() {

117

return gulp.src(mainBowerFiles())

118

.pipe(/* processing */)

119

.pipe(gulp.dest('dist/'));

120

});

121

122

// With base path for proper file structure

123

gulp.task('bower-structured', function() {

124

return gulp.src(mainBowerFiles(), { base: 'bower_components' })

125

.pipe(gulp.dest('dist/lib/'));

126

});

127

```

128

129

#### Grunt Integration

130

131

Basic Grunt usage with the main function:

132

133

```javascript

134

const mainBowerFiles = require('main-bower-files');

135

136

grunt.registerTask('copy-bower', function() {

137

const files = mainBowerFiles();

138

// Process files with grunt

139

});

140

```

141

142

### Grunt Multitask

143

144

The package provides a dedicated Grunt multitask for automatically copying Bower files using vinyl-fs.

145

146

```javascript { .api }

147

/**

148

* Grunt multitask for copying Bower packages to destination folders

149

* Task name: 'bower'

150

* @param {Object} options - Same options as main function

151

* @param {string} target.base - Base path for maintaining directory structure

152

* @param {string} target.dest - Destination directory for copied files

153

*/

154

grunt.registerMultiTask('bower', 'Copy Bower packages to the destination folder.');

155

```

156

157

**Task Configuration:**

158

159

```javascript

160

grunt.initConfig({

161

bower: {

162

dev: {

163

base: 'bower_components',

164

dest: 'web/bower_components',

165

options: {

166

checkExistence: true,

167

debugging: true,

168

paths: {

169

bowerDirectory: 'bower_components',

170

bowerrc: '.bowerrc',

171

bowerJson: 'bower.json'

172

}

173

}

174

},

175

flat: {

176

dest: 'public/vendor',

177

options: {

178

debugging: true

179

}

180

}

181

}

182

});

183

184

grunt.loadNpmTasks('main-bower-files');

185

```

186

187

**Target Properties:**

188

189

- `base`: Base path for maintaining directory structure during copy

190

- `dest`: Destination directory where files will be copied

191

- `options`: Same configuration options as the main function

192

193

### Advanced Filtering Options

194

195

#### Environment-Based File Selection

196

197

Configure different files for different environments in bower.json overrides:

198

199

```json

200

{

201

"overrides": {

202

"jquery": {

203

"main": {

204

"development": "dist/jquery.js",

205

"production": "dist/jquery.min.js"

206

}

207

}

208

}

209

}

210

```

211

212

#### Dependency Groups

213

214

Organize dependencies into groups for selective inclusion:

215

216

```json

217

{

218

"dependencies": {

219

"jquery": "*",

220

"backbone": "*",

221

"underscore": "*"

222

},

223

"group": {

224

"home": ["jquery"],

225

"admin": ["jquery", "backbone", "underscore"]

226

}

227

}

228

```

229

230

```javascript

231

// Include only home group dependencies

232

const homeFiles = mainBowerFiles({ group: 'home' });

233

234

// Include multiple groups

235

const multiFiles = mainBowerFiles({ group: ['home', 'admin'] });

236

237

// Exclude specific group

238

const excludeHome = mainBowerFiles({ group: '!home' });

239

```

240

241

### Package Overrides

242

243

Override package behavior through bower.json overrides section:

244

245

```javascript { .api }

246

/**

247

* Package override configuration

248

* @typedef {Object} PackageOverride

249

* @property {string|Array<string>|Object} [main] - Override main files

250

* @property {boolean} [ignore] - Ignore this package completely

251

* @property {Object|null} [dependencies] - Override package dependencies

252

*/

253

```

254

255

**Example override configuration:**

256

257

```json

258

{

259

"overrides": {

260

"bootstrap": {

261

"main": [

262

"less/bootstrap.less",

263

"dist/js/bootstrap.js"

264

]

265

},

266

"font-awesome": {

267

"main": [

268

"css/font-awesome.css",

269

"fonts/*"

270

]

271

},

272

"unwanted-package": {

273

"ignore": true

274

}

275

}

276

}

277

```

278

279

### Error Handling

280

281

The function throws errors in the following situations:

282

283

- bower.json file doesn't exist

284

- bower_components directory doesn't exist

285

- `checkExistence` is enabled and files don't exist

286

- Absolute paths found in bower main property

287

- Invalid dependency group specified

288

289

When using the callback pattern, errors are passed as the first argument:

290

291

```javascript

292

mainBowerFiles((err, files) => {

293

if (err) {

294

console.error('Error:', err.message);

295

return;

296

}

297

// Process files

298

});

299

```

300

301

### Path Resolution

302

303

The library resolves paths in the following order:

304

305

1. Custom `paths` option if provided

306

2. .bowerrc configuration if exists

307

3. Default bower_components location

308

4. Current working directory as fallback

309

310

All returned file paths are absolute paths ready for use with build tools.

311

312

## Dependencies

313

314

The package relies on these core dependencies:

315

316

- **chalk**: Terminal styling for debug output

317

- **extend**: Object merging utilities

318

- **globby**: Glob matching for file patterns

319

- **multimatch**: Multiple glob pattern matching

320

- **path-exists**: File existence validation

321

- **strip-json-comments**: JSON comment parsing

322

- **vinyl-fs**: Virtual file system for Grunt integration

323

324

## Internal Architecture

325

326

### PackageCollection Class

327

328

Internal class that manages the collection of bower packages and their dependencies.

329

330

```javascript { .api }

331

/**

332

* Collection for bower packages - manages dependency resolution and file collection

333

* @class PackageCollection

334

* @param {Options} opts - Configuration options

335

*/

336

function PackageCollection(opts) {

337

this.opts = opts;

338

this.debugging = opts.debugging || false;

339

this.overrides = opts.overrides || {};

340

this._packages = {};

341

this._processed = {};

342

}

343

344

PackageCollection.prototype = {

345

/**

346

* Adds a package to the collection

347

* @param {string} name - Name of the package

348

* @param {string} path - Path to the package files

349

* @param {string|Array<string>} [main] - Override main files

350

*/

351

add: function(name, path, main) { ... },

352

353

/**

354

* Gets all main files from collected packages

355

* @returns {Array<string>} Array of absolute file paths

356

*/

357

getFiles: function() { ... },

358

359

/**

360

* Collects all packages from bower.json dependencies

361

*/

362

collectPackages: function() { ... }

363

};

364

```

365

366

### Package Class

367

368

Internal class representing individual bower packages with metadata and file resolution.

369

370

```javascript { .api }

371

/**

372

* Represents a single bower package with its metadata and file resolution

373

* @class Package

374

* @param {Object} opts - Package options

375

* @param {PackageCollection} collection - Parent collection reference

376

*/

377

function Package(opts, collection) {

378

this.collection = collection;

379

this.name = opts.name || null;

380

this.path = opts.path || null;

381

this.main = opts.main || null;

382

this.dependencies = opts.dependencies;

383

this.ignore = opts.ignore || false;

384

}

385

386

Package.prototype = {

387

/**

388

* Gets main files of the package with dependency resolution

389

* @param {boolean} [force=false] - Force processing without waiting for dependencies

390

* @returns {Array<string>|false} Array of file paths or false if dependencies not ready

391

*/

392

getFiles: function(force) { ... },

393

394

/**

395

* Collects package data from bower.json, package.json, or component.json

396

*/

397

collectData: function() { ... }

398

};

399

```

400

401

### Logger Function

402

403

Internal logging utility for debug output with colored formatting.

404

405

```javascript { .api }

406

/**

407

* Logger function for debug output with colored formatting

408

* @param {...*} args - Arguments to log with colored formatting

409

*/

410

function logger(...args) { ... };

411

```