DrGodCarl DrGodCarl - 1 month ago 26
Javascript Question

Browserify/Stringify strips Knockout Comment Binding

I'm using Knockout and Browserify with Stringify. I have some Knockout bindings in comments to facilitate a custom header inside an iteration[1] in a component. Stringify strips out the comments that I need for Knockout; is there a solution for ignoring comments in a file or ignoring specific kinds of comments?

[1] - http://knockoutjs.com/documentation/foreach-binding.html (Note 4)

Answer

If you're using Browserify, you should be using Gulp. In your Stringify transform options, you should specify a custom minifyOptions object. There is an option called ignoreCustomComments where you can specify an array of regex to exclude from removal.

browserify({
    entries: 'index.js', extensions: ['.js'], watch: config.watching
  })
    .transform(babelify, {presets: ['es2015']})
    .transform(stringify, {
      appliesTo: {includeExtensions: ['.html']},
      minify: true,
      minifyOptions: {
        ignoreCustomComments: [/^(\s*ko)/, /^(\s*\/ko)/]
      }
    })

[/^(\s*ko)/, /^(\s*\/ko)/] will keep all comments that have whitespace then the 'ko' or '/ko' comment binding. However, by setting the minifyOptions to a new object, all the defaults will be overwritten to undefined; therefore, you will need to specify those now. These can be found here

Usage:

<!-- ko if: true -->
<h4>This will be shown</h4>
<!-- /ko -->

<!-- ko if: false -->
<h4>This will NOT be shown</h4>
<!-- /ko -->