如何指示grunt HTMLmin忽略PHP标记

如何指示grunt HTMLmin忽略PHP标记

问题描述:

I am using HTMLmin in my grunt.js workflow to minify my HTML.

I have a few files that also include PHP markup. For example:

<a href="<?php echo //code ?>">link</a>

HTMLmin doesn't parse this correctly, and instead throws an exception error:

Warning: [filename]
Parse Error: <a href="<?php echo //code ?>">link</a>
Aborted due to warnings.

Is there anyway to instruct HTMLmin to ignore PHP markup? I've looked through the docs but don't see any obvious answer.

The world of modern JS doesn't take into account running in a subdir or templates that go through any kind of server side manipulation. The trick would be to inject the PHP after grunt minifies with some kind of data-* attribute. I haven't developed a solution I'm fully happy with. But, you can try some grunt regex tasks to do something like this

<a data-phphref="<?= $templatePrefix;?>" data-phpclass="<?= $activeLink;?>" href="/foo/">Foo</a>

after custom grunt task

<a href="<?= $templatePrefix;?>/foo/" class="<?= $activeLink;?>">Foo</a>

Or you can do full DOM manipulation, which would probably be the better long term choice.

Update

I guess there's a 3rd option, and that would be to do token replacement to make regex easier. You can watch your source template files in a directory like ui-src/ When a change happens, run a simple search/replace for tokens

<a href="{{templatePrefix}}/foo/">Foo</a>

Output to a template directory that PHP is configured to use. This should allow you to minify like

<!-- build:js {{templatePrefix}}scripts/plugins.js -->
<script type="application/javascript" src={{templatePrefix}}components/bootstrap/js/affix.js"></script>
<!-- endbuild -->

With a grunt task like:

      "string-replace": { 
        template: { 
            files: { "./": "<%= yeoman.dist %>/*.html.php"},
            options: { 
              replacements:[ { 
                  pattern: /{{templatePrefix}}/,
                  replacement: "<?= $templatePrefix;?>"
              }
            ]
            }
        },

A bonus would be to put the PHP code snippets into a JS config file so your PHP code isn't littered throughout your Gruntfile.js

2nd Update

The preferred way to do this is have grunt-usemin inject the PHP code during the build. The recently released usemin 2.3.0 has this ability with blockReplacements.

feature request: https://github.com/yeoman/grunt-usemin/pull/337 commit: https://github.com/yeoman/grunt-usemin/commit/83f6821a30020cbc9395d7257e0276cff142e219

Basically, you can't make grunt ignore PHP, but you can make it work with PHP.