or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-rollup--plugin-inject

Rollup plugin that scans modules for global variables and injects import statements where necessary

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@rollup/plugin-inject@5.0.x

To install, run

npx @tessl/cli install tessl/npm-rollup--plugin-inject@5.0.0

0

# @rollup/plugin-inject

1

2

The @rollup/plugin-inject package is a Rollup plugin that automatically scans JavaScript modules for global variable usage and dynamically injects import statements where necessary. It provides a comprehensive solution for module dependency management by analyzing code for references to global variables (like Promise, $, fs, etc.) and automatically generating the appropriate import statements at build time.

3

4

## Package Information

5

6

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

7

- **Package Type**: npm

8

- **Language**: JavaScript (with TypeScript definitions)

9

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

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

For CommonJS:

18

19

```javascript

20

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

21

```

22

23

## Basic Usage

24

25

```javascript

26

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

27

28

export default {

29

input: 'src/index.js',

30

output: {

31

dir: 'output',

32

format: 'cjs'

33

},

34

plugins: [

35

inject({

36

// Inject jQuery as $

37

$: 'jquery',

38

39

// Inject named import

40

Promise: ['es6-promise', 'Promise'],

41

42

// Inject namespace import

43

fs: ['fs', '*'],

44

45

// Use local module

46

'Object.assign': './src/helpers/object-assign.js'

47

})

48

]

49

};

50

```

51

52

## Architecture

53

54

The plugin works by:

55

56

1. **Code Scanning**: Uses AST parsing to scan modules for global variable references

57

2. **Reference Detection**: Identifies which global variables are used but not locally defined

58

3. **Import Generation**: Automatically generates the appropriate import statements

59

4. **Code Transformation**: Injects imports at the top of modules and replaces global references

60

61

## Capabilities

62

63

### Plugin Factory Function

64

65

Creates a Rollup plugin instance configured with injection mappings.

66

67

```javascript { .api }

68

/**

69

* Creates a Rollup plugin for injecting import statements

70

* @param options - Configuration object defining injection mappings (required)

71

* @returns Rollup plugin object with transform method

72

* @throws Error if options parameter is missing, null, or undefined

73

*/

74

function inject(options: RollupInjectOptions): Plugin;

75

```

76

77

**Usage Example:**

78

79

```javascript

80

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

81

82

const plugin = inject({

83

$: 'jquery',

84

Promise: ['es6-promise', 'Promise']

85

});

86

```

87

88

### Configuration Options

89

90

Configuration interface for the inject plugin.

91

92

```typescript { .api }

93

interface RollupInjectOptions {

94

/** String-to-injection mappings for global variables */

95

[str: string]: Injectment | RollupInjectOptions['include'] | RollupInjectOptions['exclude'] | RollupInjectOptions['sourceMap'] | RollupInjectOptions['modules'];

96

97

/** File inclusion patterns (picomatch patterns) */

98

include?: string | RegExp | ReadonlyArray<string | RegExp> | null;

99

100

/** File exclusion patterns (picomatch patterns) */

101

exclude?: string | RegExp | ReadonlyArray<string | RegExp> | null;

102

103

/** Enable/disable source map generation (default: true) */

104

sourceMap?: boolean;

105

106

/** Separate injection mappings object */

107

modules?: { [str: string]: Injectment };

108

}

109

```

110

111

**Note**: The plugin also supports the `sourcemap` option (alternative spelling of `sourceMap`) for backward compatibility, but `sourceMap` is preferred.

112

113

**Configuration Examples:**

114

115

```javascript

116

// Basic injection mapping

117

{

118

$: 'jquery',

119

_: 'lodash'

120

}

121

122

// With file filtering

123

{

124

include: ['src/**/*.js'],

125

exclude: ['**/*.test.js'],

126

$: 'jquery'

127

}

128

129

// Using modules property

130

{

131

sourceMap: false,

132

modules: {

133

$: 'jquery',

134

Promise: ['es6-promise', 'Promise']

135

}

136

}

137

138

// Mixed approach (direct + modules)

139

{

140

// Direct mappings

141

$: 'jquery',

142

143

// Additional configuration

144

include: ['src/**'],

145

modules: {

146

Promise: ['es6-promise', 'Promise']

147

}

148

}

149

```

150

151

### Injection Value Types

152

153

Defines the format for injection values.

154

155

```typescript { .api }

156

type Injectment = string | [string, string];

157

```

158

159

**Injection Patterns:**

160

161

```javascript

162

// Default import: string format

163

{ $: 'jquery' }

164

// Generates: import $ from 'jquery';

165

166

// Named import: [module, export] format

167

{ Promise: ['es6-promise', 'Promise'] }

168

// Generates: import { Promise } from 'es6-promise';

169

170

// Namespace import: [module, '*'] format

171

{ fs: ['fs', '*'] }

172

// Generates: import * as fs from 'fs';

173

174

// Local module with default import (string format)

175

{ 'Object.assign': './helpers/object-assign.js' }

176

// Generates: import Object_assign from './helpers/object-assign.js';

177

178

// Local module with named import (array format)

179

{ 'Object.assign': ['./helpers/object-assign.js', 'assign'] }

180

// Generates: import { assign as Object_assign } from './helpers/object-assign.js';

181

182

// Keypath replacement

183

{ 'console.log': ['./logger', 'log'] }

184

// Replaces console.log calls with imported log function

185

```

186

187

### Plugin Object Properties

188

189

The plugin returns a Rollup plugin object with specific properties.

190

191

```javascript { .api }

192

interface Plugin {

193

/** Plugin identifier */

194

name: 'inject';

195

196

/**

197

* Transform method that processes code and injects imports

198

* @param code - Source code string

199

* @param id - Module identifier/file path

200

* @returns Transformation result or null if file should be skipped

201

*/

202

transform(code: string, id: string): TransformResult | null;

203

}

204

205

interface TransformResult {

206

/** Transformed code string */

207

code: string;

208

/** Source map (present when sourceMap option is true, null when false) */

209

map?: SourceMap | null;

210

/** AST representation (only included when no transformations occurred) */

211

ast?: any;

212

}

213

```

214

215

## Error Handling

216

217

### Configuration Errors

218

219

```javascript

220

// Throws Error if no options provided

221

inject(); // Error: Missing options

222

inject(null); // Error: Missing options

223

inject(undefined); // Error: Missing options

224

225

// Valid configurations (minimum requirement is empty object)

226

inject({}); // Valid - empty object creates plugin with no injections

227

inject({ $: 'jquery' }); // Valid - injection mapping

228

```

229

230

### Parse Errors

231

232

The plugin handles files that cannot be parsed:

233

234

- Issues warning with code `'PARSE_ERROR'`

235

- Suggests using `options.include` to restrict files

236

- Returns `null` to skip transformation on parse failure

237

- Does not throw errors for unparseable files

238

239

**Example Warning:**

240

```

241

rollup-plugin-inject: failed to parse src/binary-file.dat.

242

Consider restricting the plugin to particular files via options.include

243

```

244

245

### Module Resolution

246

247

- **Self-import prevention**: Modules cannot inject imports to themselves (returns false silently)

248

- **Path normalization**: Handles Windows path separators automatically (converts backslashes to forward slashes)

249

- **Module support**: Supports relative and absolute module paths

250

- **Format support**: Works with both CommonJS and ES modules

251

252

Example of prevented self-import:

253

```javascript

254

// In file: src/utils.js

255

inject({ utils: './utils.js' });

256

// The plugin will NOT inject an import to itself

257

```

258

259

## Advanced Usage Patterns

260

261

### File Filtering

262

263

```javascript

264

inject({

265

// Only process JavaScript files in src/

266

include: ['src/**/*.js'],

267

exclude: ['**/*.test.js', '**/*.spec.js'],

268

269

$: 'jquery',

270

_: 'lodash'

271

})

272

```

273

274

### Complex Injection Mappings

275

276

```javascript

277

inject({

278

// Multiple global variables from same module

279

Promise: ['es6-promise', 'Promise'],

280

'Promise.resolve': ['es6-promise', 'Promise'],

281

'Promise.reject': ['es6-promise', 'Promise'],

282

283

// Node.js modules

284

fs: ['fs', '*'],

285

path: ['path', '*'],

286

287

// Utility libraries

288

$: 'jquery',

289

_: 'lodash',

290

291

// Custom utilities

292

'utils.debounce': './src/utils/debounce.js',

293

'api.client': './src/api/client.js'

294

})

295

```

296

297

### Source Map Control

298

299

```javascript

300

inject({

301

// Disable source maps for better performance (both spellings supported)

302

sourceMap: false,

303

// Alternative spelling (deprecated but supported)

304

// sourcemap: false,

305

306

$: 'jquery'

307

})

308

```

309

310

## Dependencies

311

312

The plugin requires these peer and runtime dependencies:

313

314

- **Rollup**: `^1.20.0||^2.0.0||^3.0.0||^4.0.0` (peer dependency, optional)

315

- **@rollup/pluginutils**: `^5.0.1` (runtime dependency)

316

- **estree-walker**: `^2.0.2` (runtime dependency)

317

- **magic-string**: `^0.30.3` (runtime dependency)