babel-plugin-func-wrap
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.
windowa = 1; /* becomes (with args: ['window']) */ { windowa = 1;} /* becomes (with name: 'foo', args: ['window']) */ { windowa = 1;} /* becomes (with format: 'cjs', args: ['window']) */ module { windowa = 1;} /* becomes (with format: 'cjs', name: 'foo', args: ['window']) */ exports { windowa = 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.jsmoduleexports = plugins: 'func-wrap'
Alternative, configure transformations within your Babel configuration:
moduleexports = 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'