Why
Javascript
good parts recommend that a global namespace is needed to collect other variables and avoid to manage these variables directly. However rollup IIFE format cannot export an library tool to a customized namespace.
Installation
npm install -D rollup-plugin-iife-namespace
Usage
import iifeNS from 'rollup-plugin-iife-namespace'
export default {
input:'test.js',
output:{
file:'bundle.js',
format:'iife',
name:'Rollup',
banner:'/*using rollup build*/'
},
plugins:[iifeNS()]
}
// input
// test.js
export function add(a,b){
return a+b
}
// output
// bundle.js
(function(exports){
/*using rollup build*/
var Rollup = (function (exports) {
'use strict';
function add(a,b){
return a+b
}
exports.add = add;
return exports;
}({}));
exports.Rollup = Rollup
}(window||(window={})))
API
There is only one option for the plugin. When we want to customize our context, we just add a context
option.
import iifeNS from 'rollup-plugin-iife-namespace'
export default {
input:'test.js',
output:{
file:'bundle.js',
format:'iife',
name:'Rollup',
banner:'/*using rollup build*/'
},
plugins:[iifeNS({
context:'window.MyNameSpace'
})]
}
The output of test.js
is like this
(function(exports){
/*using rollup build*/
var Rollup = (function (exports) {
'use strict';
function add(a,b){
return a+b
}
exports.add = add;
return exports;
}({}));
exports.Rollup = Rollup
}(window.MyNameSpace||(window.MyNameSpace={})))