Search code examples
gulpvue.jslaravel-elixirgulp-minify

Browserify + vue + HTML minify


I'm using elixir together with browserify. In my vue components I include templates from html files, like this:

Vue.extend({
    template: require('./call.html'),
    props: {
        call: {
            type: Object,
            required: true
        }
    },
    //...

It works as expected. However, if I run gulp --production, the html is not compressed in the generated file.

What I'd like to achieve is to remove all unneeded tab, space, newline characters, comments from the included html files.

There's a package called gulp-minify-html but I don't know how if I could use this one for solving this issue.

Has anyone here done something similar to this?


Solution

  • Take a look at vueify. Minification is automatically applied on template, when compiled with NODE_ENV=production.

    You won't need to place your html in separate file in that case, as well. But you could if needed: just omit <template> block and add template to module.exports object as usual:

    <script>
        module.exports = {
            template: require('./template1.html'),
        };
    </script>
    

    Research

    So, in fact its minification is purely decorational. As follows from dependencies list, vueify depends on html-minifier.

    Let's take a look at code:

    // production minifiers
    if (process.env.NODE_ENV === 'production') {
      var htmlMinifier = require('html-minifier')
      // required for Vue 1.0 shorthand syntax
      var htmlMinifyOptions = {
        customAttrSurround: [[/@/, new RegExp('')], [/:/, new RegExp('')]]
      }
    }
    

    The only option here is customAttrSurround, thus, anything else will be taken from default values.

    Result

    We have several options here:

    1. Fix the source once. Just add your config here.
    2. Create an issue on github. Minifier config surely must be included in vue.config.js.
    3. Pull request.

    Final solution by asker

    The code above should be replaced by this:

    // production minifiers
    if (process.env.NODE_ENV === 'production') {
      var htmlMinifier = require('html-minifier')
      // required for Vue 1.0 shorthand syntax
      var htmlMinifyOptions = {
        customAttrSurround: [[/@/, new RegExp('')], [/:/, new RegExp('')]],
        collapseWhitespace: true,
        removeComments: true
      }
    }
    

    See my pull request