What is rollup-plugin-inject?
The rollup-plugin-inject package is a Rollup plugin that allows you to automatically inject variables or modules into your code. This can be useful for polyfills, shims, or any other global variables that you want to ensure are available in your bundle.
What are rollup-plugin-inject's main functionalities?
Injecting Global Variables
This feature allows you to inject global variables into your code. In this example, the $ and _ variables are injected from the 'jquery' and 'lodash' modules respectively.
const inject = require('rollup-plugin-inject');
module.exports = {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'iife'
},
plugins: [
inject({
$: 'jquery',
_: 'lodash'
})
]
};
Injecting Custom Code
This feature allows you to inject custom code from a specific file. In this example, the 'myGlobal' variable is injected from the 'src/myGlobal.js' file.
const inject = require('rollup-plugin-inject');
module.exports = {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'iife'
},
plugins: [
inject({
include: '**/*.js',
modules: {
myGlobal: 'src/myGlobal.js'
}
})
]
};
Other packages similar to rollup-plugin-inject
rollup-plugin-replace
The rollup-plugin-replace package allows you to replace strings in files while bundling. It is similar to rollup-plugin-inject in that it can be used to inject code, but it works by replacing specific strings rather than injecting variables or modules.
rollup-plugin-alias
The rollup-plugin-alias package allows you to create module aliases, which can be used to simplify import statements. While it doesn't inject variables or modules directly, it can be used to achieve similar results by aliasing modules to shorter or more convenient paths.
rollup-plugin-commonjs
The rollup-plugin-commonjs package converts CommonJS modules to ES6, so they can be included in a Rollup bundle. It is similar to rollup-plugin-inject in that it helps manage module imports, but it focuses on compatibility with CommonJS modules.
rollup-plugin-inject
Scan modules for global variables and inject import
statements where necessary
Installation
npm install --save-dev rollup-plugin-inject
Usage
import { rollup } from 'rollup';
import inject from 'rollup-plugin-inject';
rollup({
entry: 'main.js',
plugins: [
inject({
exclude: 'node_modules/**',
$: 'jquery',
Promise: [ 'es6-promise', 'Promise' ],
'Object.assign': path.resolve( 'src/helpers/object-assign.js' ),
modules: {
$: 'jquery',
Promise: [ 'es6-promise', 'Promise' ],
'Object.assign': path.resolve( 'src/helpers/object-assign.js' )
}
})
]
}).then(...)