babel-plugin-func-wrap

Wrap the whole script in a function — export as CommonJS, ES Modules, IIFE, or a global variable


Keywords
javascript, node, babel, babel-plugin, function, wrap, esm, cjs, iife, global
License
CC0-1.0
Install
npm install babel-plugin-func-wrap@1.1.0

Documentation

babel-plugin-func-wrap Babel

NPM Version Build Status Support Chat

babel-plugin-func-wrap is a Babel plugin that lets you wrap the whole script in a function, which can export as CommonJS, ES Modules, IIFE, or a global variable. This can be helpful when transforming scripts with immediately-executable code into something evocable.

window.a = 1;

/* becomes (with args: ['window']) */

export default function (window) {
  window.a = 1;
}

/* becomes (with name: 'foo', args: ['window']) */

export function foo (window) {
  window.a = 1;
}

/* becomes (with format: 'cjs', args: ['window']) */

module.exports = function (window) {
  window.a = 1;
}

/* becomes (with format: 'cjs', name: 'foo', args: ['window']) */

exports.foo = function (window) {
  window.a = 1;
}

Usage

Add babel-plugin-func-wrap to your project:

npm install babel-plugin-func-wrap --save-dev

Add babel-plugin-func-wrap to your Babel configuration:

// babel.config.js
module.exports = {
  plugins: [
    'func-wrap'
  ]
}

Alternative, configure transformations within your Babel configuration:

module.exports = {
  plugins: [
    ['func-wrap', {
      /* use a named export */
      name: 'library',

      /* assign arguments to the function */
      args: ['window'],
      
      /* export as CommonJS */
      format: 'cjs'
    }]
  ]
}

Options

args

The args option defines argument parameters passed into the wrapping function.

{
  /* export default function (argA, argB, ...argC) {} */
  args: ['argA', 'argB', '...argC']
}

format

The format option defines how the function is exported. The available options are esm (default), cjs, iife, and global.

{
  /* export default function () {} */
  format: 'esm'
}
{
  /* module.exports = function () {} */
  format: 'cjs'
}
{
  /* (function () {})() */
  format: 'iife'
}
{
  /* window.$ = function () {} */
  format: 'global',
  name: 'window.$'
}

When using global, a name must always be specified.

name

The name option defines the name of the export, which is otherwise default.

{
  /* export function foo () {} */
  name: 'foo'
}
{
  /* exports.foo = function () {} */
  format: 'cjs',
  name: 'foo'
}