Chapter 16. Concatenation and Baking
If you’ve properly set up your JavaScript files to contain one object per file, then it’s likely you have dozens of JavaScript files. Before deploying to production, it’s best to concatenate the files so there are fewer HTTP requests on the page. Exactly how many files and which files should be concatenated with which is a project-specific decision. In any case, Ant provides an easy way to concatenate multiple files.
The Task
The <concat>
task is one of
the simplest in Ant. You simply specify a destfile
attribute containing the destination
filename and then include as many <fileset>
and
<filelist>
elements as you want. At it’s simplest, you can have a
target such as:
<target name="concatenate"> <concat destfile="${build.dir}/build.js"> <fileset dir="${src.dir}" includes="**/*.js" /> </concat> </target>
This target concatenates all JavaScript files in the source directory into a single file called build.js in the build directory. Keep in mind that the files are concatenated in the order in which they appear on the filesystem (alphabetically). If you want a more specific ordering, you’ll need to specify it explicitly, such as:
<target name="concatenate"> <concat destfile="${build.dir}/build.js"> <filelist dir="${src.dir}" files="first.js,second.js" /> <fileset dir="${src.dir}" includes="**/*.js" excludes="first.js,second.js"/> </concat> </target>
This version of the target ensures that first.js is the first file added to the final file and second.js ...
Get Maintainable JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.