Code Monkey home page Code Monkey logo

squishit's Introduction

About SquishIt

SquishIt is an asset optimization library for .net web applications. It handles combining and minifying css and javascript assets through creation of bundles. There are currently extensions available that allow use of .less, coffeescript, SASS/SCSS and Hogan templates through SquishIt's preprocessor pipeline. There is also an extension that writes your combined files to Amazon S3 that can serve as a template for integrating with the CDN of your choosing.

For medium trust environments there is an option to build and cache bundles in-memory so that you don't need write permission in the application's working directory. An example of setting this up for an ASP.net MVC project can be found here. For a WebForms project the asset controller would just be replaced with an HTTP handler.

Installation

SquishIt comes as a NuGet package and can be installed via PM> Install-Package SquishIt.

Latest stable package: nuget version.

You can also download precompiled binaries from the SquishIt AppHarbor page.

Building from source

You will need to have Visual Studio and 7-Zip installed.

  1. Open Visual Studio Command Prompt
  2. cd \path\to\SquishIt\tools
  3. If necessary, add 7z.exe to your path: set PATH=%PATH%;C:\Program Files\7-Zip\
  4. Run build-package version-id (version-id can be anything you like.)

If all went well, you should have a package called tools/SquishIt-version-id.zip.

Thanks

The build is generously hosted and run on the CodeBetter TeamCity infrastructure.

Latest build status: status

We also get great tooling support from the kind folks at JetBrains

squishit's People

Contributors

0liver avatar akkuma avatar alexcuse avatar bang75 avatar buddydvd avatar chrishefley avatar cjberg avatar davidzidar avatar ferrod20 avatar gorbach avatar iaineh avatar jetheredge avatar jincod avatar kubelsmieci avatar laazyj avatar mattbeckman avatar max-arshinov avatar rdumont avatar sagacity avatar schourode avatar simonpstevens avatar stefanb avatar syndicatedshannon avatar taliesins avatar themikecom avatar thomasvm avatar troygoode avatar tucaz avatar valmont avatar wolfgang42 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

squishit's Issues

Security Exception

When I try to use it in an ASP.Net Mvc application, I get this. Tried updating the permissions on my /Scripts folder (where it should write out the combined js and css files), but to no avail. May be related to http://github.com/jetheredge/SquishIt/issues#issue/22

Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.


        <b> Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.<br><br>

AddRemote() does not allow adding only remote resources

Perhaps I misunderstand the intent of AddRemote, but I'm trying to get the following

  .AddRemote(null, "http://localhost:19435/util/WindowGlobalScript")

or

   .AddRemote("windowglobal.js", "http://localhost:19435/util/WindowGlobalScript")

but neither work

Css conditional write

It's normal to have specific css files for specific browsers, like IE. And every one use conditional elements to browsers parse like <!--[if lt IE 8]>

Being able to set the (java)script tag programatically

(Copied text from the google group) ->

I've got a scenario where I need to change the way the script tag is
rendered. We're using some font library java script files and to get
certain swedish chars to work we need to say charset="utf-8" on the
script tag. I've looked at the source of the JavscriptBundler and it
seems to me like the script tag is defined in a const that I'm not
able to affect through the API.

We can solve this now by simple not minifying these files but wouldn't
it be a good idea to be able to pass a scriptTemplate through some
overloaded ctor on the JavaScriptBundle class. I know I'm supposed to
create my own fork and send a pull request but I'm not in git-land yet
I'm afraid.

SquishIT appears to be broken with MVC3 Preview 1

Adding this in my head:

@Bundle.Css()
.Add("~/Content/Style.css")
.Add("~/Content/ButtonStyles.css")
.Add("~/Content/slide.css")
.Add("~/Content/AjaxToolTip.css")
.Add("~/Content/ui-lightness/jquery-ui-1.8.2.custom.css")
.Add("~/Content/ui.jqgrid.css")
.Render("~/css/combined_#.css")

yields this reuslt:

SquishIt.Framework.Css.CssBundle
.Add("~/Content/Style.css")
.Add("~/Content/ButtonStyles.css")
.Add("~/Content/slide.css")
.Add("~/Content/AjaxToolTip.css")
.Add("~/Content/ui-lightness/jquery-ui-1.8.2.custom.css")
.Add("~/Content/ui.jqgrid.css")
.Render("~/css/combined_#.css")

So it basically just html write it out.

File is empty when changed

I'm using this in the application_start

Bundle.JavaScript().Add("~/somescript.js").ForceRelease().AsNamed(SquishItIndex.PageData.JavaScript.SomeName, "~/Scripts/combined-master.js")

and render it with RenderNamed...

The combined file became empty when i changed the somescript.js and saved it.
I have to recompile the whole website to make it appear with the changed data.
I'm creating this issue because i don't know if this a known problem.

Im using the verision installed with nugget

Side Question:
If this is fixed and i upload a changed file to my server then in theory the file will be invalidated and recreated?

Regards
Robert

Support for @import in linked css files

In my projects I only link a single stylesheet to me master page called screen.css. The uncompressed contents of this file looks like the following:

/* import stylesheets and hide from ie/mac */
@import url("reset.css");
@import url("master.css");
@import url("ie.css");
/* end import/hide */

It would be great if I could simply call:

<%= Bundle.CssImport("~/css/NAMEOFFILE.css") %>

or

<%= Bundle.Css.AddImport("~/css/NAMEOFFILE.css") %>

And it would take all the files listed as @import and combine them into one compressed file called compressed.css_hash. The link in the master page would be NAMEOFFILE.css_hash and the contests would look like:

/* import stylesheets and hide from ie/mac */
@import url("compressed.css_hash");
/* end import/hide */

Closure compiler path exception

When attempting to use the closure compiler for JS minification by passing in ClosureMinifier.Identifier to ProcessJavaScriptInput, I'm getting an exception thrown that it can't find the minified file. Upon further investigation, this is because it can't find the closure-compiler.jar so it doesn't generate any output to find. By default it's using Assembly.GetExecutingAssembly().Location which looks in the same "Temporary ASP.NET Files" directory as the Bundler.Framework.dll, but that directory has no closure-compiler directory or .jar. I get this exception when running the default BundlerAspNetTest project with the ClosureMinifier.Identifier. I'm running .NET 3.5 on Windows 7 64-bit in case that makes a difference.

BTW I sent a pull request for a small patch I made that shortens the hashed URLs a bit by using modified base64 encoding, not sure if you got that (I'm new to git / GitHub).

Great project!

Bundle and Razor View Engine problem

When using Bundle with the new View Engine Razor from MSFT the code is not rendered but displayed on the page as a string. This is because everything in Razor is encoded by default.

This can be solved if Bundle would return a MvcHtmlString instead of just a String.

The work around with current Bundle version and Razor is:

@MvcHtmlString.Create(
Bundle.Css()
.Add("/Styles/Base.css.less")
.Add("
/Styles/Core.css.less")
.Render("~/Styles/Core.min.css"))

Could the MvcHtmlString be implemented in Bundle?

Infinite loop with CssCompressors.MsCompressor

So this isn't SquishIt's fault, but I discovered the hard way that I can send the MsCompressor bundled in 0.6.1 into an infinite loop by using one of the old school Microsoft DXImageTransforms in CSS:

    private string badCss = @"
        button
        {
            filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#30ffffff,endColorstr=#10000000) progid:DXImageTransform.Microsoft.Shadow(color=#000000,direction=135,strength=2);
        }
    ";

    [Test]
    public void BadMsCompressorTest()
    {
        var cssCompressor = CssCompressorRegistry.Get(MsCompressor.Identifier);
        var compressedCss = cssCompressor.CompressContent(badcss);
    }

The MsCompressor adds thousands and thousands of the same message (choking when it gets to '#30ffffff') in an Errors property, causing the process to consume 100% CPU and ever-increasing amounts of memory until it is killed.

I'm not sure how SquishIt can resolve this, other than to say to be careful when using the MsCompressor in its current state with these kinds of IE-specific transforms. (On our site, they're used with a lot of other browser-specific markup to get gradients on buttons.) I just thought it'd be good for everyone to know to watch out for this.

I'll report this as an issue over on the Ajax Minifier codeplex site.

The Bundle.Css().Add(css-path) do have a problem with some css class names.

Hi

i use the Sprite and Image Optimization from here http://aspnet.codeplex.com/releases/view/65787

the library simply combines images to sprites and outputs a css file.

i included this css file for squize it to include in my master css file but know it wont include the file at all and i think its because of an error while squize it works with the new generated css file.

previous versions worked until i updated it to there newest. as i used nuget to update it i canot rollback so for know until
this naming error is fixed i have to include the non squized css file :(

Here is what they changed:
the new version changed the naming of css class names and know it looks like this .icons/somePicName.png

Note that after .icons there is this 2 symbols \ and /

combined but not minified

Would it be possible to combine all the JS files but not minify them?

My app is an internal app, so the same users will use it (so file size doesn't matter since the cached copies will be used) and it is easier for me to debug issues in production with the non-minified versions of the files. I do, however, like the faster start times of a combined js files.

Framework does not work for me in a medium trust setup.

I get a "That assembly does not allow partially trusted callers." when trying to run code in medium trust. The minified file(s) are set to save in the same directory as my application (/assets/css/......) so that can't be the issue. I took a screen shot of the stack trace and hosted it at: http://funky-fresh.com/squishit.png if that helps. I get the error when I deploy to RackSpace Cloud as well as set the trust level in my web.config and test locally. Hope that helps and thanks for the good looking tool.

Media Tag For Css Is Missing

Need to be able to specify media tag for a css bundle. This feature would also be facilitated by creating groups of files, since a different media tag could be specified for the same bundle, at different times. Will need to see how this interaction will occur.

Generate to RAM

My ASP.Net app currently does not have rights to write to files. Is it possible to generate the files to RAM instead?

Not safe for use with multiple worker processes

If a Web site using Bundle.Css().Render() is running under a Web Garden (i.e., there are multiple worker processes for a single Web site), it is possible for both instances to try to generate the file at the same time because SquishIt is not using a locking mechanism that works across multiple processes. If this explicitly isn't a supported scenario, that's fine, then I can wrap the API call with a Mutex easily enough. Just thought I'd point it out. Thanks!

System.IO.IOException: The process cannot access the file 'generated-default-ie7.css' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path, Encoding encoding)
at SquishIt.Framework.Files.FileReader..ctor(String file)
at SquishIt.Framework.Files.FileReaderFactory.GetFileReader(String file)
at SquishIt.Framework.BundleBase.ReadFile(String file)
at SquishIt.Framework.Css.CssBundle.RenderRelease(String key, String renderTo)
at SquishIt.Framework.Css.CssBundle.Render(String renderTo, String key)
at SquishIt.Framework.Css.CssBundle.SquishIt.Framework.Css.ICssBundleBuilder.Render(String renderTo)

JavaScript rendering CSS Cached Asset

I've used the following code in my Global file

Bundle.CSS().Add("/foo.css").AsCached("combined");
Bundle.JavaScript().Add("
/bar.js").AsCached("combined");

And when I request the resources via

Bundle.CSS().RenderCachedAssetTag("combined");
BundleJavaScript().RenderCachedAssetTag("combined");

The resulting output is that both reference the same resource, aka the CSS registration.

Option to not write to the filesystem

In our environment we cannot write to the filesystem. It would be a shame not to use SquishIt simply because of that. Is there an option or is it possible to let SquishIt handle files on-the-fly via a handler or HTTP module? Maybe plugging into the routing system to handle versioned URLs like that are created automatically right now?

Getting Ambiguous Invocation with SquishIt MvcExtensions

When calling the RenderMvc method, it does not seem to be able to tell whether I am passing in an ICssBundleBuilder or an IJavaScriptBunderBuilder. I even tried explicitly casting, but of course that did not help.

Perhaps I am using it wrong? Could you provide a small example on how to properly use the MvcExtensions in a Razor view?

lower case url's

The hash urls are upper case, where as I have made my routes to return only lower case. This is causing issues.
I can do a toLower() after render, but then all my dev’s will have to follow the routine. Can this be made configurable?

Overloads for Add to accept a condition

I'd love to be able to have overloads for Add and AddRemote that takes parameters which are predicates.

My use-case is adding files (or not adding files) to bundles depending on some condition like IsMobileDevice or similar.

Urls with querystring parameters cause errors

This type of path...
.Add("~/client/scripts/cw.mediaplayer.js?v=1")

causes this...

[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]
System.Web.Util.UrlPath.ReduceVirtualPath(String path) +11359135
System.Web.Util.UrlPath.Reduce(String path) +171
System.Web.VirtualPath.Combine(VirtualPath relativePath) +214
System.Web.HttpRequest.MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, Boolean allowCrossAppMapping) +204
System.Web.HttpServerUtility.MapPath(String path) +252
Bundler.Framework.CssBundle.Render(String renderTo, String key) +246

AddEmbeddedResource in Debug mode

SquishIt.Framework.Bundle.JavaScript().
.AddEmbeddedResource("/Scripts/test.js", "://test.js").Render("/Scripts/test-bundle#.js");

Hi. I have digged around a little bit, but it don't seems to be obvious that in debug mode it just generates <script type="text/javascript" src="/Scripts/test.js"></script>. In Release mode it reads from the stream and create test-bundle#.js which contains content from the embedded test.js file. Everything is ok in this case. But in debug mode it doesn't write to /Scripts/test.js any content. Is it proper behavior? In my case i need to keep plenty of js script as embedded resources in different assemblies and i want Bundle to write them all to my ~/Scripts folder.

Should i add it and make a patch or there is any other solution and this behavior is ok?

weird issue with css class name "url"

Hi, love the libary, but i seem to have a strange issue with the following css:

.mc_lft ul.member_listing li a.aco span.url

that line is in a regular css file which is combined together with another css file and one less file. The minified string however changes the .url to .URl.

If i change the .url to .uri it becomes .Uri.. when i change it to something else (not reserved keyword perhaps?) like .lnk it minifies just fine..

Could this be an YUIcompressor issue (google search did not turn something up in the first few pages)?

Fixed for now by not using possibly reserved keywords as classes :)

Dotless library upgrade

Latest version of dotless has several improvements and it is desirable to update SquishIt code to utilize latest version.

Problem of upgrade exists in CssBundle's private method ProcessLess. Should be easy to rewrite in order to upgrade dotless libs to latest.

Possible (unverified) solution is:

    private string ProcessLess(string file)
    {
        var content = ReadFile(file);
        var engineFactory = new EngineFactory();            
        var engine = engineFactory.GetEngine();
        return engine.TransformToCss(content, file);
    }

Css import relative paths

When using ProcessImport() on a css that contains @import directive, relative path are handled relatively to the page, and not relatively to the css file as expected, resulting in a FileNotFound exception

Import of less files does not work

Hi

It seems that @import does not work from within .less files. This was working prior to v0.6.

I have tried different ways:

@import "file"
@import "/path2/path1/file"
@import url('file')

My attempts include using "", ", ' and with and without .less extension.

I think it is something inside the dotless framework that causes this to break. A temporary fix (not sufficient because cache invalidation of imports cannot be file dependent) is this:

    private string ProcessLess(string file)
    {
        var content = ReadFile(file);
        var engineFactory = new EngineFactory();
        var engine = engineFactory.GetEngine();

        if(processImports)
        {
            content = ProcessImport(content);
        }

        return engine.TransformToCss(content, file);
    }

Could you please verify this Justin?

CSS & Relative URIs

Problem: Relative URIs within CSS files are incorrect if the rendered CSS file is not stored in the same directory as the source CSS file.

Example:

  1. Lets say I have a directory structure like so:
~/Content
--Css
----site.css
--Js
----SomePlugin
------Images
--------blah.png
------somePlugin.js
------somePlugin.css
  1. Now lets say "somePlugin.css" has a relative reference to blah.png:

    background-image: url(images/blah.png);

  2. I want to render site.css and somePlugin.css together, and I decide to put "combined_#.css" into the ~/content/css directory.

  3. The portion of "combined_#.css" that contains the relative URI to blah.png is now broken, as the relative URI resolves to "/content/css/images/blah.png" instead of "/content/js/somePlugin/images/blah.png".

It would be ideal if SquishIt could rewrite the relative URIs to be relative to the destination of "combined_#.css".

AddRemote doubles script and link lines after refresh

Justin,

I downloaden the source code and build it, everything is okay and i run the test.
after i changed debug to false and run the test again everything looks okay but if you refresh your browser and you look at the source html then every AddRemote like is written again for each refresh you do.
So after 3 times a refresh you see in the html source:
body>
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">/script>
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">/script>
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">/script>
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">/script>
script type="text/javascript" src="/js/combined_CB3E235C3B0851DA28D136E1D5ADE8BA.js">/script>
link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jquery/jquery-ui-1.8rc3.css" />
link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jquery/jquery-ui-1.8rc3.css" />
link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jquery/jquery-ui-1.8rc3.css" />
link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jquery/jquery-ui-1.8rc3.css" />
link rel="stylesheet" type="text/css" media="screen" href="/css/combined_62D2B07CAE98A21C9F23662DBBC66F3A.css" />
link rel="stylesheet" type="text/css" media="screen" href="/combined_2725882EA6BEB1E6A547E91184A8FB0F.css" />
link rel="stylesheet" type="text/css" media="screen" href="/css/combinedimport_CCE0ED13226EC68A65F0A65CCEA873F7.css" />
link rel="stylesheet" type="text/css" media="screen" href="/combinedimport_4EE56EA0AA4DE6DA354C4A7051C3F1A6.css" />

You can see that all the AddRemote lines are repeated
(I left the < character out)

gzippedOutputFile currently disabled?

Hi,

I downloaded the latest and I noticed that the WriteJavaScriptToFile function in JavaScriptBundle.cs

   public void WriteJavaScriptToFile(string minifiedJavaScript, string outputFile, string gzippedOutputFile)
    {
        WriteFiles(minifiedJavaScript, outputFile);
        WriteGZippedFile(minifiedJavaScript, null);
    }

passes null to WriteGZippedFile. Is GZip a feature you plan to support later on, or am I missing something?

ps: Great contribution and it actually makes sense, thank you!

CDN support

It could have support to CDNs. This way all javascript references will be centralized on SquishIt.

Compression of swfobject breaks javascript in firefox

When executing swfobject in the browser it throws an error ("b.attachEvent is not a method"). This does only apply to Firefox, both chrome and internet explorer works or at least it doesn't throw error. When using ForceRelease it breaks but when using ForceDebug it works. So it seems that the compression makes something more than it ought to do.
There is already an compressed version of swfobject available that works. I can use that seperately and put a script tag below squishit rendering but then it is not bundled with the others. Maybe there should be an option for selecting which files that is compressed when using add.

Reading of files does not handle internationalization

We have files with Japanese characters in them. The StreamReader in FileReader class is not set up to handle international characters.

We've done a build replacing the initialisation with

streamReader = new StreamReader(file, System.Text.Encoding.UTF8, false);

first quote disappeared in css image tag Bundle.Css()

the orginal css before the minifie style.css
background-image: url('../../Resources/paper-background.gif');

after minife style-min.css
background-image:url(Resources/paper-background.gif'');

the first quote somehow disappeared in the processing

if the img url tag is background-image: url('../Resources/somename.jpg');

then the minified css is correct background-image:url('/Resources/somename.jpg');

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.