Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

rollup-plugin-commonjs

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rollup-plugin-commonjs - npm Package Compare versions

Comparing version 2.0.0 to 2.1.0

src/.babelrc

8

CHANGELOG.md
# rollup-plugin-commonjs changelog
## 2.1.0
* Optimised module wrappers ([#20](https://github.com/rollup/rollup-plugin-commonjs/pull/20))
* Allow control over named exports via `options.namedExports` ([#18](https://github.com/rollup/rollup-plugin-commonjs/issues/18))
* Handle bare imports correctly ([#23](https://github.com/rollup/rollup-plugin-commonjs/issues/23))
* Blacklist all reserved words as export names ([#21](https://github.com/rollup/rollup-plugin-commonjs/issues/21))
* Configure allowed file extensions via `options.extensions` ([#27](https://github.com/rollup/rollup-plugin-commonjs/pull/27))
## 2.0.0

@@ -4,0 +12,0 @@

102

dist/rollup-plugin-commonjs.cjs.js

@@ -5,2 +5,3 @@ 'use strict';

var path = require('path');
var resolve = require('resolve');
var acorn = require('acorn');

@@ -50,7 +51,9 @@ acorn = 'default' in acorn ? acorn['default'] : acorn;

var blacklistedExports = {
__esModule: true,
'default': true
};
var reserved = 'abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(' ');
var blacklistedExports = { __esModule: true };
reserved.forEach(function (word) {
return blacklistedExports[word] = true;
});
function getName(id) {

@@ -62,10 +65,38 @@ var base = path.basename(id);

}
function getCandidatesForExtension(resolved, extension) {
return [resolved + extension, resolved + (path.sep + 'index' + extension)];
}
function getCandidates(resolved, extensions) {
return extensions.reduce(function (paths, extension) {
return paths.concat(getCandidatesForExtension(resolved, extension));
}, [resolved]);
}
function commonjs() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var extensions = options.extensions || ['.js'];
var filter = rollupPluginutils.createFilter(options.include, options.exclude);
var bundleUsesGlobal = false;
var bundleRequiresWrappers = false;
var sourceMap = options.sourceMap !== false;
var customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(function (id) {
var resolvedId = undefined;
try {
resolvedId = resolve.sync(id, { basedir: process.cwd() });
} catch (err) {
resolvedId = path.resolve(id);
}
customNamedExports[resolvedId] = options.namedExports[id];
});
}
return {

@@ -76,3 +107,3 @@ resolveId: function resolveId(importee, importer) {

var resolved = path.resolve(path.dirname(importer), importee);
var candidates = [resolved, resolved + '.js', resolved + (path.sep + 'index.js')];
var candidates = getCandidates(resolved, extensions);

@@ -86,6 +117,5 @@ for (var i = 0; i < candidates.length; i += 1) {

},
transform: function transform(code, id) {
if (!filter(id)) return null;
if (path.extname(id) !== '.js') return null;
if (extensions.indexOf(path.extname(id)) === -1) return null;
if (!firstpass.test(code)) return null;

@@ -111,5 +141,10 @@

var scope = rollupPluginutils.attachScopes(ast, 'scope');
var uses = { module: false, exports: false, global: false };
var namedExports = {};
var usesModuleOrExports = undefined;
var usesGlobal = undefined;
if (customNamedExports[id]) {
customNamedExports[id].forEach(function (name) {
return namedExports[name] = true;
});
}

@@ -151,4 +186,3 @@ estreeWalker.walk(ast, {

if (node.type === 'Identifier') {
if ((node.name === 'module' || node.name === 'exports') && isReference(node, parent) && !scope.contains(node.name)) usesModuleOrExports = true;
if (node.name === 'global' && isReference(node, parent) && !scope.contains('global')) usesGlobal = true;
if (node.name in uses && !uses[node.name] && isReference(node, parent) && !scope.contains(node.name)) uses[node.name] = true;
return;

@@ -168,3 +202,3 @@ }

name = 'require$$' + uid++;
required[source] = { source: source, name: name };
required[source] = { source: source, name: name, importsDefault: false };
} else {

@@ -174,5 +208,10 @@ name = required[source].name;

magicString.overwrite(node.start, node.end, name);
if (parent.type !== 'ExpressionStatement') {
required[source].importsDefault = true;
magicString.overwrite(node.start, node.end, name);
} else {
// is a bare import, e.g. `require('foo');`
magicString.remove(parent.start, parent.end);
}
},
leave: function leave(node) {

@@ -185,13 +224,25 @@ if (node.scope) scope = scope.parent;

if (!sources.length && !usesModuleOrExports && !usesGlobal) return null; // not a CommonJS module
if (!sources.length && !uses.module && !uses.exports && !uses.global) {
if (Object.keys(customNamedExports).length) {
throw new Error('Custom named exports were specified for ' + id + ' but it does not appear to be a CommonJS module');
}
return null; // not a CommonJS module
}
bundleRequiresWrappers = true;
var name = getName(id);
var importBlock = sources.length ? sources.map(function (source) {
return 'import ' + required[source].name + ' from \'' + source + '\';';
var _required$source = required[source];
var name = _required$source.name;
var importsDefault = _required$source.importsDefault;
return 'import ' + (importsDefault ? name + ' from ' : '') + '\'' + source + '\';';
}).join('\n') : '';
var intro = '\n\nvar ' + name + ' = (function (module' + (usesGlobal ? ', global' : '') + ') {\nvar exports = module.exports;\n';
var args = 'module' + (uses.exports || uses.global ? ', exports' : '') + (uses.global ? ', global' : '');
var outro = '\nreturn module.exports;\n})({exports:{}}' + (usesGlobal ? ', __commonjs_global' : '') + ');\n\nexport default (' + name + ' && typeof ' + name + ' === \'object\' && \'default\' in ' + name + ' ? ' + name + '[\'default\'] : ' + name + ');\n';
var intro = '\n\nvar ' + name + ' = __commonjs(function (' + args + ') {\n';
var outro = '\n});\n\nexport default (' + name + ' && typeof ' + name + ' === \'object\' && \'default\' in ' + name + ' ? ' + name + '[\'default\'] : ' + name + ');\n';

@@ -209,9 +260,18 @@ outro += Object.keys(namedExports).filter(function (key) {

if (usesGlobal) bundleUsesGlobal = true;
if (uses.global) bundleUsesGlobal = true;
return { code: code, map: map };
},
intro: function intro() {
var intros = [];
intro: function intro() {
return bundleUsesGlobal ? 'var __commonjs_global = typeof window !== \'undefined\' ? window : typeof global !== \'undefined\' ? global : this;' : '';
if (bundleUsesGlobal) {
intros.push('var __commonjs_global = typeof window !== \'undefined\' ? window : typeof global !== \'undefined\' ? global : this;');
}
if (bundleRequiresWrappers) {
intros.push('function __commonjs(fn, module) { return module = { exports: {} }, fn(module, module.exports' + (bundleUsesGlobal ? ', __commonjs_global' : '') + '), module.exports; }\n');
}
return intros.join('\n');
}

@@ -218,0 +278,0 @@ };

import { statSync } from 'fs';
import { extname, basename, sep, dirname, resolve } from 'path';
import { sync } from 'resolve';
import acorn from 'acorn';

@@ -45,7 +46,9 @@ import { walk } from 'estree-walker';

var blacklistedExports = {
__esModule: true,
'default': true
};
var reserved = 'abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(' ');
var blacklistedExports = { __esModule: true };
reserved.forEach(function (word) {
return blacklistedExports[word] = true;
});
function getName(id) {

@@ -57,10 +60,38 @@ var base = basename(id);

}
function getCandidatesForExtension(resolved, extension) {
return [resolved + extension, resolved + (sep + 'index' + extension)];
}
function getCandidates(resolved, extensions) {
return extensions.reduce(function (paths, extension) {
return paths.concat(getCandidatesForExtension(resolved, extension));
}, [resolved]);
}
function commonjs() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var extensions = options.extensions || ['.js'];
var filter = createFilter(options.include, options.exclude);
var bundleUsesGlobal = false;
var bundleRequiresWrappers = false;
var sourceMap = options.sourceMap !== false;
var customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(function (id) {
var resolvedId = undefined;
try {
resolvedId = sync(id, { basedir: process.cwd() });
} catch (err) {
resolvedId = resolve(id);
}
customNamedExports[resolvedId] = options.namedExports[id];
});
}
return {

@@ -71,3 +102,3 @@ resolveId: function resolveId(importee, importer) {

var resolved = resolve(dirname(importer), importee);
var candidates = [resolved, resolved + '.js', resolved + (sep + 'index.js')];
var candidates = getCandidates(resolved, extensions);

@@ -81,6 +112,5 @@ for (var i = 0; i < candidates.length; i += 1) {

},
transform: function transform(code, id) {
if (!filter(id)) return null;
if (extname(id) !== '.js') return null;
if (extensions.indexOf(extname(id)) === -1) return null;
if (!firstpass.test(code)) return null;

@@ -106,5 +136,10 @@

var scope = attachScopes(ast, 'scope');
var uses = { module: false, exports: false, global: false };
var namedExports = {};
var usesModuleOrExports = undefined;
var usesGlobal = undefined;
if (customNamedExports[id]) {
customNamedExports[id].forEach(function (name) {
return namedExports[name] = true;
});
}

@@ -146,4 +181,3 @@ walk(ast, {

if (node.type === 'Identifier') {
if ((node.name === 'module' || node.name === 'exports') && isReference(node, parent) && !scope.contains(node.name)) usesModuleOrExports = true;
if (node.name === 'global' && isReference(node, parent) && !scope.contains('global')) usesGlobal = true;
if (node.name in uses && !uses[node.name] && isReference(node, parent) && !scope.contains(node.name)) uses[node.name] = true;
return;

@@ -163,3 +197,3 @@ }

name = 'require$$' + uid++;
required[source] = { source: source, name: name };
required[source] = { source: source, name: name, importsDefault: false };
} else {

@@ -169,5 +203,10 @@ name = required[source].name;

magicString.overwrite(node.start, node.end, name);
if (parent.type !== 'ExpressionStatement') {
required[source].importsDefault = true;
magicString.overwrite(node.start, node.end, name);
} else {
// is a bare import, e.g. `require('foo');`
magicString.remove(parent.start, parent.end);
}
},
leave: function leave(node) {

@@ -180,13 +219,25 @@ if (node.scope) scope = scope.parent;

if (!sources.length && !usesModuleOrExports && !usesGlobal) return null; // not a CommonJS module
if (!sources.length && !uses.module && !uses.exports && !uses.global) {
if (Object.keys(customNamedExports).length) {
throw new Error('Custom named exports were specified for ' + id + ' but it does not appear to be a CommonJS module');
}
return null; // not a CommonJS module
}
bundleRequiresWrappers = true;
var name = getName(id);
var importBlock = sources.length ? sources.map(function (source) {
return 'import ' + required[source].name + ' from \'' + source + '\';';
var _required$source = required[source];
var name = _required$source.name;
var importsDefault = _required$source.importsDefault;
return 'import ' + (importsDefault ? name + ' from ' : '') + '\'' + source + '\';';
}).join('\n') : '';
var intro = '\n\nvar ' + name + ' = (function (module' + (usesGlobal ? ', global' : '') + ') {\nvar exports = module.exports;\n';
var args = 'module' + (uses.exports || uses.global ? ', exports' : '') + (uses.global ? ', global' : '');
var outro = '\nreturn module.exports;\n})({exports:{}}' + (usesGlobal ? ', __commonjs_global' : '') + ');\n\nexport default (' + name + ' && typeof ' + name + ' === \'object\' && \'default\' in ' + name + ' ? ' + name + '[\'default\'] : ' + name + ');\n';
var intro = '\n\nvar ' + name + ' = __commonjs(function (' + args + ') {\n';
var outro = '\n});\n\nexport default (' + name + ' && typeof ' + name + ' === \'object\' && \'default\' in ' + name + ' ? ' + name + '[\'default\'] : ' + name + ');\n';

@@ -204,9 +255,18 @@ outro += Object.keys(namedExports).filter(function (key) {

if (usesGlobal) bundleUsesGlobal = true;
if (uses.global) bundleUsesGlobal = true;
return { code: code, map: map };
},
intro: function intro() {
var intros = [];
intro: function intro() {
return bundleUsesGlobal ? 'var __commonjs_global = typeof window !== \'undefined\' ? window : typeof global !== \'undefined\' ? global : this;' : '';
if (bundleUsesGlobal) {
intros.push('var __commonjs_global = typeof window !== \'undefined\' ? window : typeof global !== \'undefined\' ? global : this;');
}
if (bundleRequiresWrappers) {
intros.push('function __commonjs(fn, module) { return module = { exports: {} }, fn(module, module.exports' + (bundleUsesGlobal ? ', __commonjs_global' : '') + '), module.exports; }\n');
}
return intros.join('\n');
}

@@ -213,0 +273,0 @@ };

{
"name": "rollup-plugin-commonjs",
"version": "2.0.0",
"version": "2.1.0",
"description": "Convert CommonJS modules to ES2015",
"devDependencies": {
"babel-preset-es2015": "^6.3.13",
"babel-preset-es2015-rollup": "^1.0.0",
"babel-register": "^6.3.13",
"eslint": "^1.7.3",
"mocha": "^2.3.3",
"rollup": "^0.20.3",
"rollup-plugin-babel": "^1.0.0",
"rollup": "^0.22.0",
"rollup-plugin-babel": "^2.2.0",
"rollup-plugin-npm": "^1.1.0",
"source-map": "^0.5.3"

@@ -15,3 +19,3 @@ },

"scripts": {
"test": "mocha",
"test": "mocha --compilers js:babel-register",
"pretest": "npm run build",

@@ -29,3 +33,4 @@ "build": "rm -rf dist/* && rollup -c -f cjs -o dist/rollup-plugin-commonjs.cjs.js && rollup -c -f es6 -o dist/rollup-plugin-commonjs.es6.js",

"estree-walker": "^0.2.0",
"magic-string": "^0.8.0",
"magic-string": "^0.10.0",
"resolve": "^1.1.6",
"rollup-pluginutils": "^1.2.0"

@@ -32,0 +37,0 @@ },

@@ -34,3 +34,7 @@ # rollup-plugin-commonjs

include: 'node_modules/**',
exclude: [ 'node_modules/foo/**', 'node_modules/bar/**' ]
exclude: [ 'node_modules/foo/**', 'node_modules/bar/**' ],
// search for files other than .js files (must already
// be transpiled by a previous plugin!)
extensions: [ '.js', '.coffee' ] // defaults to [ '.js' ]
})

@@ -41,5 +45,41 @@ ]

### Custom named exports
This plugin will attempt to create named exports, where appropriate, so you can do this...
```js
// importer.js
import { named } from './exporter.js';
// exporter.js
module.exports = { named: 42 }; // or `exports.named = 42;`
```
...but that's not always possible:
```js
// importer.js
import { named } from 'my-lib';
// my-lib.js
var myLib = exports;
myLib.named = 'you can\'t see me';
```
In those cases, you can specify custom named exports:
```js
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'node_modules/my-lib/index.js': [ 'named' ]
}
});
```
## License
MIT
import { statSync } from 'fs';
import { basename, dirname, extname, resolve, sep } from 'path';
import { sync as nodeResolveSync } from 'resolve';
import acorn from 'acorn';

@@ -12,7 +13,7 @@ import { walk } from 'estree-walker';

var blacklistedExports = {
__esModule: true,
default: true
};
const reserved = 'abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split( ' ' );
var blacklistedExports = { __esModule: true };
reserved.forEach( word => blacklistedExports[ word ] = true );
function getName ( id ) {

@@ -25,8 +26,39 @@ const base = basename( id );

function getCandidatesForExtension ( resolved, extension ) {
return [
resolved + extension,
resolved + `${sep}index${extension}`
];
}
function getCandidates ( resolved, extensions ) {
return extensions.reduce(
( paths, extension ) => paths.concat( getCandidatesForExtension ( resolved, extension ) ),
[resolved]
);
}
export default function commonjs ( options = {} ) {
const extensions = options.extensions || ['.js'];
const filter = createFilter( options.include, options.exclude );
let bundleUsesGlobal = false;
let bundleRequiresWrappers = false;
const sourceMap = options.sourceMap !== false;
let customNamedExports = {};
if ( options.namedExports ) {
Object.keys( options.namedExports ).forEach( id => {
let resolvedId;
try {
resolvedId = nodeResolveSync( id, { basedir: process.cwd() });
} catch ( err ) {
resolvedId = resolve( id );
}
customNamedExports[ resolvedId ] = options.namedExports[ id ];
});
}
return {

@@ -37,7 +69,3 @@ resolveId ( importee, importer ) {

const resolved = resolve( dirname( importer ), importee );
const candidates = [
resolved,
resolved + '.js',
resolved + `${sep}index.js`
];
const candidates = getCandidates( resolved, extensions );

@@ -54,3 +82,3 @@ for ( let i = 0; i < candidates.length; i += 1 ) {

if ( !filter( id ) ) return null;
if ( extname( id ) !== '.js' ) return null;
if ( extensions.indexOf( extname( id ) ) === -1 ) return null;
if ( !firstpass.test( code ) ) return null;

@@ -76,5 +104,8 @@

let scope = attachScopes( ast, 'scope' );
let uses = { module: false, exports: false, global: false };
let namedExports = {};
let usesModuleOrExports;
let usesGlobal;
if ( customNamedExports[ id ] ) {
customNamedExports[ id ].forEach( name => namedExports[ name ] = true );
}

@@ -116,4 +147,3 @@ walk( ast, {

if ( node.type === 'Identifier' ) {
if ( ( node.name === 'module' || node.name === 'exports' ) && isReference( node, parent ) && !scope.contains( node.name ) ) usesModuleOrExports = true;
if ( node.name === 'global' && isReference( node, parent ) && !scope.contains( 'global' ) ) usesGlobal = true;
if ( ( node.name in uses && !uses[ node.name ] ) && isReference( node, parent ) && !scope.contains( node.name ) ) uses[ node.name ] = true;
return;

@@ -133,3 +163,3 @@ }

name = `require$$${uid++}`;
required[ source ] = { source, name };
required[ source ] = { source, name, importsDefault: false };
} else {

@@ -139,3 +169,9 @@ name = required[ source ].name;

magicString.overwrite( node.start, node.end, name );
if ( parent.type !== 'ExpressionStatement' ) {
required[ source ].importsDefault = true;
magicString.overwrite( node.start, node.end, name );
} else {
// is a bare import, e.g. `require('foo');`
magicString.remove( parent.start, parent.end );
}
},

@@ -150,22 +186,25 @@

if ( !sources.length && !usesModuleOrExports && !usesGlobal ) return null; // not a CommonJS module
if ( !sources.length && !uses.module && !uses.exports && !uses.global ) {
if ( Object.keys( customNamedExports ).length ) {
throw new Error( `Custom named exports were specified for ${id} but it does not appear to be a CommonJS module` );
}
return null; // not a CommonJS module
}
bundleRequiresWrappers = true;
const name = getName( id );
const importBlock = sources.length ?
sources.map( source => `import ${required[ source ].name} from '${source}';` ).join( '\n' ) :
sources.map( source => {
const { name, importsDefault } = required[ source ];
return `import ${importsDefault ? `${name} from ` : ``}'${source}';`;
}).join( '\n' ) :
'';
const intro = `
const args = `module${uses.exports || uses.global ? ', exports' : ''}${uses.global ? ', global' : ''}`;
var ${name} = (function (module${usesGlobal ? ', global' : ''}) {
var exports = module.exports;
`;
const intro = `\n\nvar ${name} = __commonjs(function (${args}) {\n`;
let outro = `\n});\n\nexport default (${name} && typeof ${name} === 'object' && 'default' in ${name} ? ${name}['default'] : ${name});\n`;
let outro = `
return module.exports;
})({exports:{}}${usesGlobal ? ', __commonjs_global' : ''});
export default (${name} && typeof ${name} === 'object' && 'default' in ${name} ? ${name}['default'] : ${name});\n`;
outro += Object.keys( namedExports )

@@ -184,3 +223,3 @@ .filter( key => !blacklistedExports[ key ] )

if ( usesGlobal ) bundleUsesGlobal = true;
if ( uses.global ) bundleUsesGlobal = true;

@@ -191,7 +230,15 @@ return { code, map };

intro () {
return bundleUsesGlobal ?
`var __commonjs_global = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this;` :
'';
var intros = [];
if ( bundleUsesGlobal ) {
intros.push( `var __commonjs_global = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this;` );
}
if ( bundleRequiresWrappers ) {
intros.push( `function __commonjs(fn, module) { return module = { exports: {} }, fn(module, module.exports${bundleUsesGlobal ? ', __commonjs_global' : ''}), module.exports; }\n` );
}
return intros.join( '\n' );
}
};
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc