From dbbfc67a0ba3b9f17e0c8ce87b30ece61790538a Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Sat, 25 Jul 2015 10:27:31 -0400 Subject: [PATCH] expand shorthand properties (#61) --- src/Statement.js | 22 ++++++++++++++----- test/function/shorthand-properties/_config.js | 3 +++ test/function/shorthand-properties/foo.js | 7 ++++++ test/function/shorthand-properties/main.js | 8 +++++++ 4 files changed, 34 insertions(+), 6 deletions(-) create mode 100644 test/function/shorthand-properties/_config.js create mode 100644 test/function/shorthand-properties/foo.js create mode 100644 test/function/shorthand-properties/main.js diff --git a/src/Statement.js b/src/Statement.js index 7cfbebf..8ed70b0 100644 --- a/src/Statement.js +++ b/src/Statement.js @@ -337,18 +337,28 @@ export default class Statement { replacementStack.push( newNames ); } - // We want to rewrite identifiers (that aren't property names etc) if ( node.type !== 'Identifier' ) return; + + // if there's no replacement, or it's the same, there's nothing more to do + const name = names[ node.name ]; + if ( !name || name === node.name ) return; + + // shorthand properties (`obj = { foo }`) need to be expanded + if ( parent.type === 'Property' && parent.shorthand ) { + magicString.insert( node.end, `: ${name}` ); + parent.key._skip = true; + parent.value._skip = true; // redundant, but defensive + return; + } + + // property names etc can be disregarded if ( parent.type === 'MemberExpression' && !parent.computed && node !== parent.object ) return; if ( parent.type === 'Property' && node !== parent.value ) return; if ( parent.type === 'MethodDefinition' && node === parent.key ) return; // TODO others...? - const name = names[ node.name ]; - - if ( name && name !== node.name ) { - magicString.overwrite( node.start, node.end, name ); - } + // all other identifiers should be overwritten + magicString.overwrite( node.start, node.end, name ); }, leave ( node ) { diff --git a/test/function/shorthand-properties/_config.js b/test/function/shorthand-properties/_config.js new file mode 100644 index 0000000..deb929d --- /dev/null +++ b/test/function/shorthand-properties/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'expands shorthand properties as necessary (#61)' +}; diff --git a/test/function/shorthand-properties/foo.js b/test/function/shorthand-properties/foo.js new file mode 100644 index 0000000..25941fc --- /dev/null +++ b/test/function/shorthand-properties/foo.js @@ -0,0 +1,7 @@ +function bar () { + return 'foo-bar'; +} + +export var foo = { + bar +}; diff --git a/test/function/shorthand-properties/main.js b/test/function/shorthand-properties/main.js new file mode 100644 index 0000000..5118a11 --- /dev/null +++ b/test/function/shorthand-properties/main.js @@ -0,0 +1,8 @@ +import { foo } from './foo'; + +function bar () { + return 'main-bar'; +} + +assert.equal( bar(), 'main-bar' ); +assert.equal( foo.bar(), 'foo-bar' );