Question

I'm using Ant to minimize all the JS files in my project. It compiles my various JS files (ie: file1.js, file2.js, file3.js) into a single file (ie: file.min.js) and then copies this minimized version along with my HTML source files in a build folder.

It works great but the HTML source files that get copied to the build folder still reference the old un-minimized versions (file1.js, file2.js, etc...)

So my question is, is there a function/feature to change any related file references in the HTML source code when I run the Ant build?

Était-ce utile?

La solution

The easiest way would be to simply always use the minified JS. This works great as long as you never need to run your JS through a debugger or get comprehensible backtraces.

A technology called "source maps" solves this problem. If you use source maps, you can always use the minified version, and when you need to debug, the debugger loads the un-minified version on-demand. Unfortunately, source maps are very new as of this writing (March 2013), and the technology requires support from both the browser and the minifier.

If your HTML is produced from templates, you'd be better off passing a setting into the template to tell it whether you're building development or production, and then have the header text changed accordingly.

If none of the above solutions are appropriate for you, a hacky solution to your problem would be to mark separate comments in your HTML like this:

<!-- BEGIN DEVELOPMENT -->
<script src="src/js/file1.js"></script>
<script src="src/js/file2.js"></script>
<script src="src/js/file3.js"></script>
<!-- END DEVELOPMENT -->

<!-- BEGIN PRODUCTION
<script src="dist/js/file.js.min"></script>
     END PRODUCTION -->

Then have Ant run some sed scripts to comment out the development statements and add the production statements:

# run this command to create production version of project.html
cat src/html/project.html                                       \
| sed -e 's/<!-- BEGIN DEVELOPMENT -->/<!-- BEGIN DEVELOPMENT/' \
| sed -e 's/<!-- END DEVELOPMENT -->/     END DEVELOPMENT -->/' \
| sed -e 's/<!-- BEGIN PRODUCTION/<!-- BEGIN PRODUCTION -->/'   \
| sed -e 's/     END PRODUCTION -->/<!-- END PRODUCTION -->/'   \
> dist/html/project.html

I suggest putting this command into a shell script and having Ant run the script with execfile. There might also be third-party tasks for this kind of substitution in ant-contrib or elsewhere, but using them will be a pain for anyone who builds your code, because they'll have to install the same ant extension you use.

If you're building on a non-UNIX-like system that lacks sed (i.e., Windows), you might be able to use the Windows version of sed from the gnuwin32 project. Or just build on Linux in a Virtualbox VM

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top