/rollup-plugin-codefilter

A plugin for rollup/vite to filter code by dotenv variables

Primary LanguageJavaScriptMIT LicenseMIT

rollup-plugin-codefilter

This is a plugin for rollup/vite that filter code by dotenv variables. It allows user to use // ifdef {env variable} // endifcomment to keep or skrip code. For example:

// ifdef DEV
if (process.env.DEV) {
  console.log('dev')
}
// endif

If a DEV variable in dotenv and the value of it is true string, the code between ifdef and endif comment will be preserved. Otherwise, it will be removed.

install

npm install rollup-plugin-codefilter --save-dev

quick start

create a rollup.config.js configuration file and import the plugin:

import codeFilter from 'rollup-plugin-codefilter'

module.exports = {
  input: 'index.js',
  output: {
    file: 'bundle.js',
    format: 'iife',
    name: 'test'
  },
  plugins: [
    codeFilter()
  ]
}

create a .env configuration file and define some true or false variables.

keep = true
discard = false

create index.js:

function log () {
  // ifdef keep
  console.log('hello world!')
  // endif

  // ifdef discard
  console.log('it will be discarded.')
  // endif
}

export default log

Finally, run rollup -c rollup.config.js.
The file will be generated in folder dist:

var test = (function () {
  'use strict';

  function log () {
    console.log('hello world!');
  }

  return log;

}());

options

ext

Type: Array<string> Default: [js, json]

Only handle the module which match the provided extension. Currently only support js and json.

dotenv

Refer to dotenv's options

exclude

Type: String | Array<String>
Default: null

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default no files are ignored.

include

Type: String | Array<String>
Default: null

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.


The options below are the same as @rollup/plugin-json's.

To be careful, you can't use @rollup/plugin-json when this plugin injected.

indent

Type: String
Default: '\t'

Specifies the indentation for the generated default export.

namedExports

Type: Boolean
Default: true

If true, instructs the plugin to generate a named export for every property of the JSON object.

preferConst

Type: Boolean
Default: false

If true, instructs the plugin to declare properties as variables, using either var or const. This pertains to tree-shaking.