Introduction to Rollup Plugin Replace
rollup-plugin-replace
is a powerful plugin for Rollup that allows you to replace strings in files while bundling your application. This can be extremely useful for various situations such as environment configuration, feature flags, and conditional compilation.
Key Features and API Examples
This plugin provides several useful APIs to handle different replacement scenarios.
Basic Replacement
To replace a string, you can use the simplest form of the replace
method:
import replace from 'rollup-plugin-replace'; export default { plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('development') }) ] };
Using Regular Expressions
Sometimes you may want to use regular expressions for more complex replacements:
import replace from 'rollup-plugin-replace'; export default { plugins: [ replace({ include: 'src/**', delimiters: ['', ''], values: { 'foo(\\d+)': (match, pattern) => parseInt(match, 10) }, }) ] };
Environment Variables Replacement
You can also replace environment variables in your codebase:
import replace from 'rollup-plugin-replace'; export default { plugins: [ replace({ 'process.env.API_KEY': JSON.stringify(process.env.API_KEY) }) ] };
Multiple Replacements
Sometimes you need to perform multiple replacements:
import replace from 'rollup-plugin-replace'; export default { plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('production'), 'myVariable': JSON.stringify('This is my variable value') }) ] };
Practical Application Example
Here is a practical example of how to use rollup-plugin-replace
in an application:
// rollup.config.js import replace from 'rollup-plugin-replace'; import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; export default { input: 'src/main.js', output: { file: 'dist/bundle.js', format: 'cjs' }, plugins: [ resolve(), commonjs(), replace({ 'process.env.NODE_ENV': JSON.stringify('production'), 'process.env.API_KEY': JSON.stringify(process.env.API_KEY), '__VERSION__': '1.0.0' }) ] };
App Example
Let’s create a simple app that uses the rollup-plugin-replace
plugin for two different environments:
// src/main.js if (process.env.NODE_ENV === 'development') { console.log('This is a development build'); } else if (process.env.NODE_ENV === 'production') { console.log('This is a production build'); } console.log('API Key:', process.env.API_KEY); console.log('App Version:', __VERSION__);
When you run Rollup to build your project, the strings will be replaced accordingly, allowing for environment-specific code execution.
Hash: ae40f936db66b5d550ba936e0ab8b5ba4bfb26dd03ddcc8c6a9a246c9c77153d