javascriptmakefilejscompress

Makefile which compresses javascript


I want to compress javascript in yui compressor, How to write Make file for compress javascript.

Because grammar is difficult and does not understand it, Could you give me a sample Makefile for me?


Solution

  • Your makefile would look something like

    code.compressed.js: code.js
        compressor -o $@ $<
    

    Note that the second line is indented with a tab character, not just spaces. The make utility cares about this.

    code.compressed.js is the name that the file should be written to, code.js is the file to compress, and compressor is the program doing the compression.

    The -o flag indicates the output file, following the convention of compilers and similar tools. Yours may differ; check its documentation.

    The variable $@ is Makefile shorthand for "this rule's target", code.compressed.js in this case. Similarly, $< is an abbreviation for "this rule's first dependency". These variables are useful so that you needn't repeat yourself, nor make duplicate changes when files get renamed.

    If you have multiple files that will all be compressed into a single output file, you can put them all on the dependency line, and then use the special variable $^ in the build rule to specify all of them:

    code.compressed.js: code1.js code2.js
        compressor -o $@ $^
    

    Alternately, if you want them each compressed separately, you can write a pattern rule and use it for all of them:

    TARGETS = code1.cjs code2.cjs code3.cjs
    
    all: $(TARGETS)
    
    %.cjs: %.js
        compressor -o $@ $<
    

    Make defaults to building the first target that it sees, which is all in this case. The list of files to compress to is given by the contents of the TARGET variable. The % is a wildcard that make will substitute to generate rules for matching source and target file names.