vitaly-t / decomment

:hammer: Removes comments from JSON, JavaScript, CSS, HTML, etc.
75 stars 21 forks source link

Ignoring a single multi-line comment #17

Closed ashclarke closed 6 years ago

ashclarke commented 6 years ago

Hi, I have a regular expression that looks for a particular comment to ignore: \/\*![^]*?(?=app-name)[^]*?\*\/ (https://regex101.com/r/sQ9EtT/1)

As you can see, this is designed to match a single important comment containing app-name, located at the start of the file (index 0):

/*!
 * app-name - This is a description.
 * http://www.website.com
 * Version: 1.0.0
 */

It should not match any other multiline comment, such as:

/*!
 * app-nope - This is a description.
 * http://www.website.com
 * Version: 1.0.0
 */

or: /*! hi */.

I have the following config for decomment:

{
    ignore: new RegExp("\/\*![^]*?(?=app-name)[^]*?\*\/", "i"),
    trim: true
}

I'm finding that the comment is removed anyway (Note: I wouldn't expect it to but, for completeness, trim: false does not fix the issue).

I console.logged the parser in my node_modules folder and I have the following:

console.log(reg):
    /\/*![^]*?(?=app-name)[^]*?\*\//i

console.log(JSON.stringify(code.substr(match.index, match[0].length - 1))):
    "!\r\n * app-name - This is a description.\r\n * http://www.website.com\r\n * Version: 1.0.0\r\n *"

console.log(JSON.stringify(code.substr(match.index, match[0]))):

    "!\r\n * app-name - This is a description.\r\n * http://www.website.com\r\n * Version: 1.0.0\r\n */"

It seems like the index is off - can you confirm?

vitaly-t commented 6 years ago

Why are you trying to remove comment blocks that are clearly marked as not for removal?

ashclarke commented 6 years ago

I’m trying to remove all comment blocks except our file header, on a concatenated file.

vitaly-t commented 6 years ago

It may have something to do with the fact that your regex isn't repeated. See the example, I am using flag /g in the end for repeated search.

ashclarke commented 6 years ago

I tried adding the g flag, but it had no effect.

I then removed the g flag (as I am only trying to remove one instance of this regex), removed the ! as well and the comment was successfully ignored.

Not sure if this is expected behaviour but I'm not precious about the ! and can work with this - I can also tell UglifyJS to ignore any comment containing the app name, for the minified version of the file.

vitaly-t commented 6 years ago

In general, you shouldn't try to delete /*! comments. If you want comments deleted, you should use either /* or /** for those ;)