Skip to content
This repository has been archived by the owner on Aug 4, 2021. It is now read-only.

Commit

Permalink
Merge pull request #32 from rollup/gh-31
Browse files Browse the repository at this point in the history
rewrite top-level this expressions
  • Loading branch information
Rich-Harris committed Jan 18, 2016
2 parents 2430da9 + fc4e80f commit be714d6
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,12 @@ export default function commonjs ( options = {} ) {
customNamedExports[ id ].forEach( name => namedExports[ name ] = true );
}

let scopeDepth = 0;

walk( ast, {
enter ( node, parent ) {
if ( node.scope ) scope = node.scope;
if ( /^Function/.test( node.type ) ) scopeDepth += 1;

if ( sourceMap ) {
magicString.addSourcemapLocation( node.start );
Expand Down Expand Up @@ -143,6 +146,12 @@ export default function commonjs ( options = {} ) {
return;
}

if ( node.type === 'ThisExpression' && scopeDepth === 0 ) {
uses.global = true;
magicString.overwrite( node.start, node.end, `__commonjs_global`, true );
return;
}

if ( node.type !== 'CallExpression' ) return;
if ( node.callee.name !== 'require' || scope.contains( 'require' ) ) return;
if ( node.arguments.length !== 1 || node.arguments[0].type !== 'Literal' ) return; // TODO handle these weird cases?
Expand Down Expand Up @@ -170,6 +179,7 @@ export default function commonjs ( options = {} ) {

leave ( node ) {
if ( node.scope ) scope = scope.parent;
if ( /^Function/.test( node.type ) ) scopeDepth -= 1;
}
});

Expand Down
5 changes: 5 additions & 0 deletions test/samples/this/foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = function augmentThis () {
this.x = 'x';
};

this.y = 'y';
7 changes: 7 additions & 0 deletions test/samples/this/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
var foo = require( './foo' );

var obj = {};
foo.call( obj );

assert.equal( obj.x, 'x' );
assert.equal( this.y, 'y' );
7 changes: 7 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,11 @@ describe( 'rollup-plugin-commonjs', () => {
assert.equal( executeBundle( bundle ).exports, 42 );
});
});

it.only( 'rewrites top-level this expressions', () => {
return rollup({
entry: 'samples/this/main.js',
plugins: [ commonjs() ]
}).then( executeBundle );
});
});

0 comments on commit be714d6

Please sign in to comment.