Giter Club home page Giter Club logo

packr's Introduction

Packr is a Ruby implementation of Dean Edwards’ JavaScript compressor, Packer. It can remove comments and whitespace, compress variable names, obfuscate _private identifiers, and base-62 encode your programs. It can also generate source maps, which lets your browser trace log messages and errors back to the original source, even when running minified code.

Usage

Packr provides both a command-line interface and a Ruby API. To call it from the command line (use packr --help to see available options):

packr my_script.js > my_script.min.js

To call from within a Ruby program:

require 'packr'

code = File.read('my_script.js')
compressed = Packr.pack(code)
File.open('my_script.min.js', 'w') { |f| f.write(compressed) }

This method takes a number of options to control compression, for example:

compressed = Packr.pack(code, :shrink_vars => true, :base62 => true)

The full list of available options is:

  • :minify – set to false to prevent any compression; this is useful if you just want to use Packr.bundle to concatenate files and generate a source map

  • :shrink_vars – set to true to compress local variable names

  • :private – set to true to obfuscate ‘private’ identifiers, i.e. names beginning with a single underscore

  • :base62 – encode the program using base 62

  • :protect – an array of variable names to protect from compression

  • :header – an optional string to prepend to the output, e.g. for copyright comments

Here’s an example using all of these:

compressed = Packr.pack(code,
  :shrink_vars => true,
  :private     => true,
  :protect     => %w[$super self],
  :header      => '/* Copyright 2012 some guy */'
)

Bundling and source maps

Packr also provides an API for bundling several files together and generating a single output file and source map. For example, given these two files:

# example_a.js

1. // When the minified code is loaded into a browser, you should see the call to
2. // console.log() attributed to example_a.js:4
3. 
4. console.log('Hello from file A');

and

# example_b.js

1. var display = function(message) {
2.   alert(message + ' from file B');
3. };
4. 
5. display('Ahoy there');

it can generate a combined output file:

# example-min.js

/* Copyright 2012 */
console.log('Hello from file A');var display=function(a){alert(a+' from file B')};display('Ahoy there');
//@ sourceMappingURL=example-min.js.map

and a source map:

# example-min.js.map

{
  "version": 3,
  "file": "example-min.js",
  "sourceRoot": "",
  "sources": ["../example_a.js", "../example_b.js"],
  "names": ["message"],
  "mappings": ";AAGA,QAAQ,KAAK,MAAM,KAAK,KAAK,ICH7B,IAAI,QAAU,SAASA,GACrB,MAAMA,IAAY,KAAK,KAAK,KAG9B,SAAS,KAAK;"
}

To do this, you use the bundle method, passing an array of input files and a single output file, and the compression options you want to use.

Packr.bundle %w[example_a.js example_b.js], 'min/example-min.js',
  :shrink_vars => true,
  :header      => '/* Copyright 2012 */'

On the command line, this looks like:

packr example_a.js example_b.js -o min/example-min.js -h '/* Copyright 2012 */' --shrink-vars

Notes

This program is not a JavaScript parser, and rewrites your files using regular expressions. Be sure to include semicolons and braces everywhere they are required so that your program will work correctly when packed down to a single line.

By far the most efficient way to serve JavaScript over the web is to use Packr with the --shrink-vars flag, combined with gzip compression.

If you really cannot serve gzip files, use the --base62 option to further compress your code. This mode is at its best when compressing large files with many repeated tokens.

The --private option can be used to stop other programs calling private methods in your code by renaming anything beginning with a single underscore. Beware that you should not use this if the generated file contains ‘private’ methods that need to be accessible by other files. Also know that all the files that access any particular private method must be compressed together so they all get the same rewritten name for the private method.

License

(The MIT License)

Copyright © 2004-2012 Dean Edwards, James Coglan

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.

packr's People

Contributors

jcoglan 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

Watchers

 avatar  avatar  avatar  avatar  avatar

packr's Issues

In Chrome 46.0.2490.86 / Firefox 42, the minimized code with base62 encode does not work.

In Chrome 46.0.2490.86 / Firefox 42, the minimized code with base62 encode does not work.

when executing the generated source, it shows "Uncaught TypeError: Cannot set property length of # which has only a getter"

document.getElementsByTagName('script') returns Array Like object depending on the kinds of browser. Then I suppose to replace from

document.getElementsByTagName('script')

to

Array.apply(null,document.getElementsByTagName('script'))

Packr 1.0.2 intermittently strips spaces with ruby 1.8.7 patch > p352

I just thought I'd document this issue here, but I recently upgraded to ruby 1.8.7 (2012-02-08 MBARI 8/0x6770 on patchlevel 358) [i686-darwin12.2.1], MBARI 0x6770, Ruby Enterprise Edition 2012.02

With the new version packr intermittently strips all spaces from javascript code (but not in strings). For example expected compressed output:

if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={}} ...

actual output:

if(typeofYAHOO=="undefined"||!YAHOO){varYAHOO={}} ...

This behaviour only occurs intermittently for certain runs of the ruby runtime. If the bug is happening, then all usages of Packr.pack will exhibit the behaviour while ruby is running. For another run of ruby, the bug doesn't happen at all.

I believe the problem lies with packr being dependant on hash ordering somewhere. Versions of ruby > 1.8.7 p352 return random hash orderings as per this security fix.

Unfortunately this bug took me a long time to track down because I didn't initially realise it was related to a ruby upgrade which had happened a long time previously.

Anyway, I suggest this at least be documented somewhere and preferably fixed, though I realise 1.0.2 is very old now. Not sure if the problem manifests in newer versions.

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.