Skip to content

Commit c1e672e

Browse files
joaosamoucoJosé Magalhães
authored andcommitted
mangle now receives a callback to be called when a name should be renamed or not
1 parent 19916c7 commit c1e672e

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/esshorten.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@
8585
const run = (scope, options) => {
8686
let generator = new NameGenerator(scope, options);
8787

88+
const shouldRename = options && options.shouldRename || () => true;
89+
8890
if (scope.isStatic()) {
8991
let name = '9';
9092

@@ -116,12 +118,16 @@
116118

117119
for (let def of variable.identifiers) {
118120
// change definition's name
119-
def.name = name;
121+
if (shouldRename(def.name)) {
122+
def.name = name;
123+
}
120124
}
121125

122126
for (let ref of variable.references) {
123127
// change reference's name
124-
ref.identifier.name = name;
128+
if (shouldRename(ref.identifier.name)) {
129+
ref.identifier.name = name;
130+
}
125131
}
126132
}
127133
}

test/mangle.coffee

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,26 @@ describe 'mangle:', ->
161161
distinguishFunctionExpressionScope: yes
162162
expect(result.body[0].expression.id.name).to.equal 'a'
163163
expect(result.body[0].expression.body.body[0].declarations[0].id.name).to.equal 'a'
164+
165+
describe '`shouldRename` option:', ->
166+
it 'renames by default', ->
167+
program = esprima.parse '(function name() { var foo, bar, baz; });'
168+
result = esshorten.mangle program
169+
170+
expect(result.body[0].expression.id.name).to.equal 'a'
171+
172+
it 'renames if it returns `true`', ->
173+
program = esprima.parse '(function name() { var foo, bar, baz; });'
174+
result = esshorten.mangle program,
175+
shouldRename: (id) ->
176+
return id == 'name'
177+
178+
expect(result.body[0].expression.id.name).to.equal 'a'
179+
180+
it 'does not rename if it returns `false`', ->
181+
program = esprima.parse '(function name() { var foo, bar, baz; });'
182+
result = esshorten.mangle program,
183+
shouldRename: (id) ->
184+
return id != 'name'
185+
186+
expect(result.body[0].expression.id.name).to.equal 'name'

0 commit comments

Comments
 (0)