Skip to content
Permalink
Browse files

fix typeof require === "function" && require (#77, #83)

  • Loading branch information...
Rich-Harris committed Sep 17, 2016
1 parent 88e3966 commit ed56c9b14ce5399e6b7302dc0b8f6be2b322cf16
Showing with 19 additions and 11 deletions.
  1. +4 −0 src/helpers.js
  2. +7 −11 src/transform.js
  3. +5 −0 test/function/typeof-require/foo.js
  4. +3 −0 test/function/typeof-require/main.js
@@ -3,6 +3,10 @@ export const HELPERS_ID = '\0commonjsHelpers';
export const HELPERS = `
export var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
export function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
export function unwrapExports (x) {
return x && x.__esModule ? x['default'] : x;
}
@@ -59,7 +59,7 @@ export default function transform ( code, id, isEntry, ignoreGlobal, customNamed
let uid = 0;

let scope = attachScopes( ast, 'scope' );
const uses = { module: false, exports: false, global: false };
const uses = { module: false, exports: false, global: false, require: false };

let lexicalDepth = 0;
let programDepth = 0;
@@ -126,16 +126,6 @@ export default function transform ( code, id, isEntry, ignoreGlobal, customNamed
return;
}

// To allow consumption of UMD modules, transform `typeof require` to `'function'`
if ( node.type === 'UnaryExpression' && node.operator === 'typeof' && node.argument.type === 'Identifier' ) {
const name = node.argument.name;

if ( name === 'require' && !scope.contains( name ) ) {
magicString.overwrite( node.start, node.end, `'function'` );
return;
}
}

if ( node.type === 'Identifier' ) {
if ( isReference( node, parent ) && !scope.contains( node.name ) ) {
if ( node.name in uses ) {
@@ -144,6 +134,10 @@ export default function transform ( code, id, isEntry, ignoreGlobal, customNamed
magicString.overwrite( node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, true );
}

if ( node.name === 'require' ) {
magicString.overwrite( node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, true );
}

// if module or exports are used outside the context of an assignment
// expression, we need to wrap the module
if ( node.name === 'module' || node.name === 'exports' ) {
@@ -189,6 +183,8 @@ export default function transform ( code, id, isEntry, ignoreGlobal, customNamed
// is a bare import, e.g. `require('foo');`
magicString.remove( parent.start, parent.end );
}

node.callee._skip = true;
},

leave ( node ) {
@@ -0,0 +1,5 @@
if ( typeof require === 'function' && require ) {
module.exports = 1;
} else {
module.exports = 2;
}
@@ -0,0 +1,3 @@
import foo from './foo.js';

assert.equal( foo, 1 );

0 comments on commit ed56c9b

Please sign in to comment.
You can’t perform that action at this time.