diff --git a/README.md b/README.md index 5ff19a3c..7b4d6059 100644 --- a/README.md +++ b/README.md @@ -633,6 +633,8 @@ If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.u - `unsafe_methods` (default: false) -- Converts `{ m: function(){} }` to `{ m(){} }`. `ecma` must be set to `6` or greater to enable this transform. + If `unsafe_methods` is a RegExp then key/value pairs with keys matching the + RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a "`` is not a constructor" TypeError should any code try to `new` the former function. diff --git a/lib/compress.js b/lib/compress.js index 0ac4e9a7..4e753627 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -4867,7 +4867,10 @@ merge(Compressor.prototype, { // p:async function(){} ---> async p(){} // p:()=>{} ---> p(){} // p:async()=>{} ---> async p(){} - if (compressor.option("unsafe_methods") && compressor.option("ecma") >= 6) { + var unsafe_methods = compressor.option("unsafe_methods"); + if (unsafe_methods + && compressor.option("ecma") >= 6 + && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) { var key = self.key; var value = self.value; var is_arrow_with_block = value instanceof AST_Arrow diff --git a/test/compress/properties.js b/test/compress/properties.js index 32781fa0..4cd838bb 100644 --- a/test/compress/properties.js +++ b/test/compress/properties.js @@ -999,3 +999,56 @@ issue_2321: { ] node_version: ">=6" } + +unsafe_methods_regex: { + options = { + ecma: 6, + unsafe_methods: /^[A-Z1]/, + } + input: { + var f = { + 123: function(){ console.log("123") }, + foo: function(){ console.log("foo") }, + bar() { console.log("bar") }, + Baz: function(){ console.log("baz") }, + BOO: function(){ console.log("boo") }, + null: function(){ console.log("null") }, + undefined: function(){ console.log("undefined") }, + }; + f[123](); + new f.foo(); + f.bar(); + f.Baz(); + f.BOO(); + new f.null(); + new f.undefined(); + } + expect: { + var f = { + 123() { console.log("123") }, + foo: function(){ console.log("foo") }, + bar() { console.log("bar"); }, + Baz() { console.log("baz") }, + BOO() { console.log("boo") }, + null: function(){ console.log("null") }, + undefined: function(){ console.log("undefined") }, + }; + f[123](); + new f.foo(); + f.bar(); + f.Baz(); + f.BOO(); + new f.null(); + new f.undefined(); + } + expect_stdout: [ + "123", + "foo", + "bar", + "baz", + "boo", + "null", + "undefined", + ] + node_version: ">=6" +}