Giter VIP home page Giter VIP logo

grunt-closure-compiler's Introduction

grunt-closure-compiler

A Grunt task for Closure Compiler.

Getting Started

First you need to download a build of Closure Compiler or build it from the source (see details below).

Optionally, you can set up an environment variable called CLOSURE_PATH that points to your Closure Compiler dir (see details below).

Install this module on your project's grunt.js gruntfile:

$ npm install grunt-closure-compiler

Then register the task by adding the following line to your grunt.js gruntfile:

grunt.loadNpmTasks('grunt-closure-compiler');

Then you can minify JavaScript calling:

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      closurePath: '/src/to/closure-compiler',
      js: 'static/src/frontend.js',
      jsOutputFile: 'static/js/frontend.min.js',
      maxBuffer: 500,
      options: {
        compilation_level: 'ADVANCED_OPTIMIZATIONS',
        language_in: 'ECMASCRIPT5_STRICT'
      }
    }
  }
});

closurePath is required if you choose not to set up the CLOSURE_PATH environment variable. In this case, it should point to the install dir of Closure Compiler (not the subdirectory where the compiler.jar file is located).

js property is always required.

If jsOutputFile property is set, the script will be minified and saved to the file specified. Otherwise it will be output to the command line.

maxBuffer property

If the buffer returned by closure compiler is more than 200kb, you will get an error saying "maxBuffer exceeded". To prevent this, you can set the maxBuffer to the preffered size you want (in kb)

Use cwd to specify the working directory where closure compiler is called. Useful in when you want to process common js modules.

Optionally, several parameters can be passed to options object.

Documentation

Closure Compiler installation from source

Install dependencies:

$ sudo apt-get install git ant openjdk-7-jdk

Then checkout the source from Git and build:

$ git clone https://code.google.com/p/closure-compiler/
$ cd closure-compiler
$ ant

To refresh your build, simply call:

$ git pull
$ ant clean
$ ant

Mac

Mac users can install it from brew:

$ brew install closure-compiler

Set up the environment variable

Setting up a CLOSURE_PATH environment variable is preferred because:

  • You don't have to specify the closurePath each time.
  • It makes it easy to use contributed externs.

In case you're wondering, Closure Compiler utilizes continuous integration, so it's unlikely to break.

If you create the CLOSURE_PATH environment variable, make sure to have it pointing to the closure-compiler dir created earlier (and not to the build subdirectory where the jar is located).

Mac

On Mac, when installed with brew, you can get the install path using:

$ brew --prefix closure-compiler
/usr/local/Cellar/closure-compiler/20120710

Just append /libexec to what you get. In this example, you should use the following path:

/usr/local/Cellar/closure-compiler/20120710/libexec/

Minification report

By default, a report file is generated next to the built file.

You can specify the path and name where the report will be saved using the reportFile property.

To deactivate report creation, set noreport to true.

js property

This task is a multi task, you can specify several targets. The task can minify many scripts at a time.

js can be an array if you need to concatenate several files to a target.

You can use Grunt <%= somePropInitConfig.sub.sub.prop %> or * based syntax to have the file list expanded:

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      js: 'static/src/frontend.js',
      jsOutputFile: 'static/js/frontend.min.js',
    },
    frontend_debug: {
      js: [
        '<%= closure-compiler.frontend.js %>',
        // Will expand to 'static/src/frontend.js'
        'static/src/debug.*.js'
        // Will expand to 'static/src/debug.api.js',
        //   'static/src/debug.console.js'...
      ],
      jsOutputFile: 'static/js/frontend.debug.js',
      options: {
        debug: true,
        formatting: 'PRETTY_PRINT'
      }
    },
  }
});

options properties

Properties in options are mapped to Closure Compiler command line. Just pass options as a map of option-value.

If you need to pass the same options several times, make it an array. See define below:

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      js: 'static/src/frontend.js',
      jsOutputFile: 'static/js/frontend.min.js',
      options: {
        compilation_level: 'ADVANCED_OPTIMIZATIONS',
        language_in: 'ECMASCRIPT5_STRICT',
        define: [
          '"DEBUG=false"',
          '"UI_DELAY=500"'
        ],
      }
    }
  }
});

When defining externs, if you added the CLOSURE_PATH environment variable you can easily reference Closure Compiler builtin externs using <%= process.env.CLOSURE_PATH %> Grunt template:

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      js: 'static/src/frontend.js',
      jsOutputFile: 'static/js/frontend.min.js',
      options: {
        externs: '<%= process.env.CLOSURE_PATH %>/contrib/externs/jquery-1.7.js',
      }
    }
  }
});

Otherwise, use the <%= %> Grunt template:

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      closurePath: '/src/to/closure-compiler',
      js: 'static/src/frontend.js',
      jsOutputFile: 'static/js/frontend.min.js',
      options: {
        externs: '<%= closure-compiler.frontend.closurePath %>/contrib/externs/jquery-1.7.js'
      }
    }
  }
});

To specify boolean options (such as process_common_js_modules, i.e. no value are required), set its value to undefined (or null):

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      js: 'static/src/frontend.js',
      jsOutputFile: 'static/js/frontend.min.js',
      options: {
        process_common_js_modules: undefined,
        common_js_entry_module: 'exports'
      }
    }
  }
});

For automatic resolving common js modules you can use

grunt.initConfig({
  'closure-compiler': {
    frontend: {
      cwd: 'static/src/'
      js: '*.js',
      jsOutputFile: 'static/js/frontend.min.js',
      options: {
        common_js_entry_module: 'frontend.js',
        transform_amd_modules: undefined,
        process_common_js_modules: undefined
      }
    }
  }
});

Note

grunt-closure-compiler initial development was founded by Dijiwan.

The directory structure was inspired by grunt-less, a Grunt task for Less.

License

Copyright (c) 2013 Guillaume Marty

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

grunt-closure-compiler's People

Contributors

callmevlad avatar devinrhode2 avatar draftkraft avatar gjersvik avatar gmarty avatar leorbarth avatar madhums avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-closure-compiler's Issues

No Source Map Support

I like this plugin, but I'm finding the lack of source maps too limiting. Source Maps exist in Closure Compiler, seems like it'd be a quick thing to add in.

Use java_home in path to java

It would be useful to use the JAVA_HOME variable for environments which have multiple versions of java installed.

No files

I hope someone can help explain what is missing here. I follow examples to make a basic config:

'closure-compiler': {
    frontend: {
        js: ['src/*.js'],
        jsOutputFile: 'www/<%= pkg.name %>.js',
        options: {
            compilation_level: 'ADVANCED_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT'
        }
    }
},

But the output of grunt -v is:

Running "closure-compiler:frontend" (closure-compiler) task
Verifying property closure-compiler.frontend exists in config...OK
File: [no files]

Looks like grunt is looking for files to pass to the closure-compiler grunt plugin.

Not working with brew on OSX

Installing closure compiler on OSX with brew leads to 2 things:

  • a binary available in the path as closure (symlink to /usr/local/Cellar/closure-compiler/<version>/bin/closure
  • a jar available in /usr/local/Cellar/closure-compiler/<version>/libexec/compiler.jar

The binary is only a shorthand:

#!/bin/bash
java -jar "/usr/local/Cellar/closure-compiler/20120305/libexec/compiler.jar" "$@"

I see 2 problems:

  • command variable hardcodes 'build/compiler.jar'
  • CLOSURE_PATH would necessary only
    • if closure is not available system wide
    • or if a specific version needs to be provided

undefined externs cause indexOf error.

Here's the config i was using..

'closure-compiler': {
    frontend: {
        js: [
            'js/libs/augment.js',
            'js/libs/list.js',
            'js/libs/classList.js',
            'js/script.js'
        ],
        jsOutputFile: 'js/script.min.js',
        options: {
            'create_source_map':'./script.min.js.map',
            'source_map_format':'V3'
        }
    }
}

No support for closure-compiler NPM package

There is a NPM package for closure-compiler, which makes installing it much easier (npm install...).

This package installs the jar in node_modules/closure-compiler/lib/vendor/compiler.jar

Since the last directory is called vendor, but grunt-closure-compiler always expects "build", so it will never work.

Please provide support for the closure-compiler NPM package.

@ sourceMappingURL comment

Hi

I'm working with source maps and I have a problem.

The closure compile didn't add a comment like this to te generated file.

//@ sourceMappingURL=app.map

This comment is necessary when debugging with chrome or firefox to show the original files.
I haven't found an options to tell the compiler to generate that.

Maybe it could be an option of this plugin, since it know the generated file path and the source map path. It is only necessary to append a comment like that at the end of the file.

setting closurePath

if 'closurePath' is a direct filepath to the closure jar file you should make it so it can use that instead of concatenating /build/compiler.jar at the end all the time.

Option avoid report.txt file creation

Kindly consider this small update to add an option to allow avoid .report.txt file creation.

    // Check for report file 
    if (typeof data.createReport === 'undefined') {
        data.createReport = true;
    } else {
        data.createReport = false;
    }

...

    if(data.createReport) {
      // Write compile report to a file.
      fs.writeFile(reportFile, stderr, function(err) {
        if (err) {
          grunt.warn(err);
          done(false);
        }

        grunt.log.writeln('A report is saved in ' + reportFile + '.');
        done();
      });
    }

Test on different OSes

The task is currently tested and used on Ubuntu only.

We should test it on Mac and Windows and fix accordingly.
If required, docs should be updated as well.

How to compile js files and put them into the same directory

I need to compile all files in js folder and put them into the same one with the same names. So I have the following structure:

So my compile-compiler task is:

'closure-compiler': {
   js: 'js/*.js',
   jsOutputFile: 'js/*
}

But I get the following error:

Duplicate input js\app.js

Add support for Node 8 (update grunt version)

Currently grunt-closure-compiler relies on [email protected]

Unfortunately that is not compatible with Node 8 and will cause the following error:

npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.

Seems like the fix is as easy as just updating package.json to point at a more recent version of grunt (which relies on graceful-fs).

"Cannot read: --js_output_file"

I'm using Ubuntu, I've specified the path to GCC, but when running the task I get this error:

→ grunt closure-compiler
Running "closure-compiler:frontend" (closure-compiler) task
<WARN> Command failed: ERROR - Cannot read: --js_output_file

1 error(s), 0 warning(s)
 Use --force to continue. </WARN>

Aborted due to warnings.

The task (I adapted it from the readme, and just changed the paths):

  'closure-compiler': {
    frontend: {
      js: 'first.js',
      jsOutputFile: 'second.js',
      options: {
        compilation_level: 'ADVANCED_OPTIMIZATIONS',
        language_in: 'ECMASCRIPT5_STRICT'
      }
    }
  }

Both files exist.

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

CLOSURE_PATH location issues on Win7

Hello All,

I've tried every variation I can think of to get this working. I've used the closurePath param, I've used system variables, but I cannot get this task to run without it failing, telling me that it cannot find the jar.

Is anyone else having issues on Windows or is it just me? My grunt.js file is in a root directory. I've added a 'Closure Compiler' directory with the compiler.jar file inside. It's one level up. Here are some example values I've set for the closurePath -

closurePath: '',

closurePath: '/',

closurePath: 'Closure Compiler',

closurePath: '/Closure Compiler',

closurePath: 'Closure Compiler/',

closurePath: '/Closure Compiler/',

closurePath: 'Closure Compiler/compiler',

closurePath: '/Closure Compiler/compiler',

closurePath: 'Closure Compiler/compiler.jar',

closurePath: '/Closure Compiler/compiler.jar',

Nothing works. I've tried every variation I thought it could be. Here's my object as it stands now:

'closure-compiler' : {
frontend: {
closurePath : 'Closure Compiler/',
js : 'components/footer.js',
jsOutputFile: 'js/footer.min.js',
maxBuffer : 500,
options : {
compilation_level: 'SIMPLE_OPTIMIZATIONS'
}
}
},

solo js case

Hi, is possible to setup this nice grunt takst to !compile - I want to choose from array next *.js and then compress and change to *.min.js but I dont wont copress all my js into one...
step by step
jsOutputFiles
someting like:

grunt.initConfig({
'closure-compiler': {
frontend: {
closurePath: '/src/to/closure-compiler',
js: 'static/',

  jsOutputFiles: 'static/js/',
  maxBuffer: 500,
  options: {
    compilation_level: 'ADVANCED_OPTIMIZATIONS',
    language_in: 'ECMASCRIPT5_STRICT'
  }
}

}
});
thanks! :)

specify relative path to compiler jar?

Can I specify a path to the compiler jar in the options instead?
This works better for a project where I have multiple contributors and I dont want to have them set up ENV variables on all their machines

Enhancement: change compilation levels for certain files.

In trying to successfully use advanced compilation for a project but one of my dependencies flat out breaks when I use advanced compilation, and there's not much I can swiftly do about it. I can use advanced compilation on my stuff just fine, but need to use simple compilation for my other dependency.

Not an easy thing to do my any means, but I just wanted to write it down somewhere relevant.

Include Closure

It would be nice if this didn't require Closure to be installed separately. Like the other grunt compiler-tasks (LESS, SASS, uglify, etc). Just 'npm install grunt-closure-compiler', done!

Task hangs if file is nonexistant

Running "closureCompiler:jsTemplates" (closureCompiler) task
Executing: java -jar node_modules/grunt-htmlcompressor/ext/compiler.jar --js_output_file=built/production/js/templates.js --compilation_level SIMPLE_OPTIMIZATIONS --language_in ECMASCRIPT5

Task should make sure file exists before running.

Closure Compiler installation from source is out of date

The README is out of date as:

Also the code is out of date as:

  • The build process now outputs the jar to {closurePath}/target/closure-compiler*.jar, rather than {closurePath}/build/compiler.jar. In my case the file was {closurePath}/target/closure-compiler-1.0-SNAPSHOT.jar.

    We should probably take this into consideration in #38

Warning: Missing js property. Use --force to continue.

I'm trying to run a build and I keep seeing this warning. Here is my task:

'closure-compiler': {
            frontend: {
                closurePath: '/tools',
                js: '/en/2014/js/award_tiles.js',
                jsOutputFile: '/en/2014/js/vlp.min.js',
                options: {
                    compilation_level: 'SIMPLE_OPTIMIZATIONS'
                }
            }
        }

Please advise.

Command failed: java.io.FileNotFoundException

Hi!
I started use this package with this config:

'closure-compiler': {
    scripts: {
        closurePath     : 'js/helpers/closure-compiler/',
        js              : 'js/scripts.js',
        jsOutputFile    : 'js/scripts.min.js',
        options: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS'
        }
    }
}

But getting error:
'Warning: Command failed: java.io.FileNotFoundException:path\to\file\scripts.min.js'
preent screen

Minified target file is created but is empty..

Any ideas how can I overcome this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.