-->

Combine and minify templates with CoffeeScript / C

2020-07-31 21:24发布

问题:

I have a src/templates/ directory full of mustache templates. How would I combine and minify the contents of those, so they're available for use in my CoffeeScript app?

I'm already following the directions at https://github.com/jashkenas/coffee-script/wiki/%5BHowTo%5D-Compiling-and-Setting-Up-Build-Tools for combining and minifying my CoffeeScript src into js.

回答1:

First off, I'll assume that your templates are being exported to the global object (e.g. each one does window.userpane = rather than just userpane =). That's the most important thing. If you're doing that, and you're concatenating and compiling successfully, then the only thing left is to have automatic minification after each concatenation.

Short answer: There's no good tool for this yet. Your best option is to extend your existing Cakefile with a line like

fs.watchFile 'concatenated.js', ->
  exec 'uglifyjs concatenated.js'

(To install UglifyJS, run npm install uglify-js.)

Now, this won't solve the problem of ensuring that your scripts are concatenated in a sensible order. (For instance, if you have window.templates = {} in file A and templates.userpane = in file B, then it's very important that file A be concatenated before file B.) For that, you should keep an eye on Sprockets, which lets you indicate at the top of each JS file what its dependencies are, then combine them in an order that respects those dependencies. The creator of Sprockets, Sam Stephenson, is an active member of the CoffeeScript community, and first-class support for CoffeeScript in Sprockets is coming in Sprockets 2 (repo here).

Update: Here's a Cake task to do the actual reading and concatenating of everything in the template directory:

templateJs = ''
files = fs.readdirSync 'template'
for file in files
  contents = fs.readFileSync file, 'utf8'
  name = file.replace /\..*/, '' # remove extension
  templateJs += "window.#{name} = '#{contents}';"

Then prepend your concatenated JS with templateJs. Note that this assumes that there are no single quotes (') in the template. Either put backslashes in front of them or consistently use double quotes.