Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A bundler and minifier for ASP.NET Core

License

NotificationsYou must be signed in to change notification settings

ligershark/WebOptimizer

Repository files navigation

Build statusNuGet

ASP.NET Core middleware for bundling and minification of CSS and JavaScript files at runtime. With full server-side and client-side caching to ensure high performance. No complicated build process and no hassle.

Check out thedemo website or itssource code.

Versions

Master is being updated forASP.NET Core 3.0ForASP.NET Core 2.x, use the2.0 branch.

Content

How it works

WebOptimizer sets up a pipeline for static files so they can be transformed (minified, bundled, etc.) before sent to the browser. This pipeline is highly flexible and can be used to combine many different transformations to the same files.

For instance, the pipeline for a single .css file could be orchestrated to first goes through minification, then through fingerprinting and finally through image inlining before being sent to the browser.

WebOptimizer makes sure that the pipeline is orchestrated for maximum performance and compatability out of the box, yet at the same time allows for full customization and extensibility.

The pipeline is set up when the ASP.NET web application starts, but no output is being generated until the first time they are requested by the browser. The output is then being stored in memory and served very fast on all subsequent requests. This also means that no output files are being generated on disk.

Install and setup

Add the NuGet packageLigerShark.WebOptimizer.Core to any ASP.NET Core 2.0 project.

dotnet add package LigerShark.WebOptimizer.Core

Then inStartup.cs, addapp.UseWebOptimizer() to theConfigure method anywhere beforeapp.UseStaticFiles (if present), like so:

publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){if(env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseWebOptimizer();app.UseStaticFiles();app.UseMvc(routes=>{routes.MapRoute(name:"default",template:"{controller=Home}/{action=Index}/{id?}");});}

That sets up the middleware that handles the requests and transformation of the files.

And finally modify theConfigureServices method by adding a call toservices.AddWebOptimizer():

publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddWebOptimizer();}

The service contains all the configuration used by the middleware and allows your app to interact with it as well.

That's it. You have now enabled automatic CSS and JavaScript minification. No other code changes are needed for enabling this.

Try it by requesting one of your .css or .js files in the browser and see if it has been minified.

Disabling minification:
If you want to disable minification (e.g. in development), the following overload for AddWebOptimizer() can be used:

if (env.IsDevelopment()){    services.AddWebOptimizer(minify#"auto">

Minification

To control the minification in more detail, we must interact with the pipeline that manipulates the file content.

Minification is the process of removing all unnecessary characters from source code without changing its functionality in order to make it as small as possible.

For example, perhaps we only want a few certain JavaScript files to be minified automatically. Then we would write something like this:

publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddWebOptimizer(pipeline=>{pipeline.MinifyJsFiles("js/a.js","js/b.js","js/c.js");});}

Notice that the paths to the .js files are relative to the wwwroot folder.

We can do the same for CSS, but this time we're using a globbing pattern to allow minification for all .css files in a particular folder and its sub folders:

pipeline.MinifyCssFiles("css/**/*.css");

When using globbing patterns, you still request the .css files on their relative path such ashttp://localhost:1234/css/site.css.

Setting up automatic minification like this doesn't require any other code changes in your web application to work.

Under the hood, WebOptimizer usesNUglify to minify JavaScript and CSS.

Bundling

To bundle multiple source file into a single output file couldn't be easier.

Bundling is the process of taking multiple source files and combining them into a single output file. All CSS and JavaScript bundles are also being automatically minified.

Let's imagine we wanted to bundle/css/a.css and/css/b.css into a single output file and we want that output file to be located athttp://localhost/css/bundle.css.

Then we would call theAddCssBundle method:

services.AddWebOptimizer(pipeline=>{pipeline.AddCssBundle("/css/bundle.css","css/a.css","css/b.css");});

TheAddCssBundle method will combine the two source files in the order they are listed and then minify the resulting output file. The output file/css/bundle.css is created and kept in memory and not as a file on disk.

To bundle all files from a particular folder, we can use globbing patterns like this:

services.AddWebOptimizer(pipeline=>{pipeline.AddCssBundle("/css/bundle.css","css/**/*.css");});

When using bundling, we have to update our<script> and<link> tags to point to the bundle route. It could look like this:

<linkrel="stylesheet"href="/css/bundle.css"/>

Content Root vs. Web Root

By default, all bundle source files are relative to the Web Root (wwwroot) folder, but you can change it to be relative to the Content Root instead.

The Content Root folder is usually the project root directory, which is the parent directory ofwwwroot.

As an example, lets create a bundle of files found in a folder called node_modules that exist in the Content Root:

services.AddWebOptimizer(pipeline=>{pipeline.AddCssBundle("/css/bundle.css","node_modules/jquery/dist/*.js").UseContentRoot();});

TheUseContentRoot() method makes the bundle look for source files in the Content Root rather than in the Web Root.

To use a completely customIFileProvider, you can use theUseFileProvider pipeline method.

services.AddWebOptimizer(pipeline=>{varprovider=newMicrosoft.Extensions.FileProviders.PhysicalFileProvider(@"C:\path\to\my\root\folder");pipeline.AddJavaScriptBundle("/js/scripts.js","a.js","b.js").UseFileProvider(provider);});

Tag Helpers

WebOptimizer ships with a fewTag Helpers that helps with a few important tasks.

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files.

First, we need to register the TagHelpers defined inLigerShark.WebOptimizer.Core in our project.

To do that, go to_ViewImports.cshtml and register the Tag Helpers by adding@addTagHelper *, WebOptimizer.Core to the file.

@addTagHelper *, WebOptimizer.Core@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Cache busting

As soon as the Tag Helpers are registered in your project, you'll notice how the<script> and<link> tags starts to render a little differently when they are referencing a file or bundle.

NOTE: Unlike other ASP.NET Core Tag Helpers,<script> and<link> tags don't need anasp- attribute to be rendered as a Tag Helper.

They will get a version string added as a URL parameter:

<linkrel="stylesheet"href="/css/bundle.css?v=OFNUnL-rtjZYOQwGomkVMwO415EOHtJ_Tu_s0SIlm9s"/>

This version string changes every time one or more of the source files are modified.

NOTE: TagHelpers will only work on files registered as assets on the pipeline (will not work for all files in your and tags out of the blue). make sure to add all required files as assets (glob is supported to add wildcard paths).

services.AddWebOptimizer(pipeline=>{pipeline.AddFiles("text/javascript","/dist/*");pipeline.AddFiles("text/css","/css/*");});

This technique is calledcache busting and is a critical component to achieving high performance, since we cannot utilize browser caching of the CSS and JavaScript files without it. That is also why it can not be disabled when using WebOptimizer.

HTTPS Compression Considerations

When utilized with theservices.AddResponseCompression middleware included in theFeature, it's important to note that by default thecache busted assets may not be included as theResponse Header: content-type is modified from the defaultapplication/javascript totext/javascript, which is not a supported defaultResponseCompressionDefaults.MimeTypes before ASP.NET Core 7.0 and can be added in theStartup.ConfigureServices like so:

services.AddResponseCompression( options=>{options.MimeTypes=ResponseCompressionDefaults.MimeTypes.Concat(new[]{"text/javascript"});});

Note:app.UseResponseCompression() should be used prior toapp.UseWebOptimizer()

Note: If you're usingASP.NET Core 7.0 or later, you don't need to add this, as support fortext/javascript is included by default.

Inlining content

We can also use Web Optimizer to inline the content of the files directly into the Razor page. This is useful for creating high-performance websites that inlines the above-the-fold CSS and lazy loads the rest later.

To do this, simply add the attributeinline to any<link> or<script> element like so:

<linkrel="stylesheet"href="/css/bundle.css"inline/><scriptsrc="/any/file.js"inline></script>

There is a Tag Helper that understands what theinline attribute means and handles the inlining automatically.

Compiling Scss

WebOptimizer can also compileScss files into CSS. For that you need to install theLigerShark.WebOptimizer.Sass NuGet package and hooking it up is a breeze. Read more on theWebOptimizer.Sass website.

Options

You can control the options from the appsettings.json file or in code

{"webOptimizer": {"enableCaching":true,"enableMemoryCache":true,"enableDiskCache":true,"cacheDirectory":"/var/temp/weboptimizercache","enableTagHelperBundling":true,"cdnUrl":"https://my-cdn.com/","allowEmptyBundle":false  }}
services.AddWebOptimizer(pipeline=>{pipeline.AddCssBundle("/css/bundle.css","css/*.css");pipeline.AddJavaScriptBundle("/js/bundle.js","js/plus.js","js/minus.js");},    option=>{option.EnableCaching=true;option.EnableDiskCache=false;option.EnableMemoryCache=true;option.AllowEmptyBundle=true;});

enableCaching determines if thecache-control HTTP headers should be set and if conditional GET (304) requests should be supported. This could be helpful to disable while in development mode.

Default:true

enableTagHelperBundling determines if<script> and<link> elements should point to the bundled path or a reference per source file should be created. This is helpful to disable when in development mode.

Default:true

enableMemoryCache determines if theIMemoryCache is used for caching. Can be helpful to disable while in development mode.

Default:true

enableDiskCache determines if the pipeline assets are cached to disk. This can speed up application restarts by loading pipline assets from the disk instead of re-executing the pipeline. Can be helpful to disable while in development mode.

Default:true

cacheDirectory sets the directory where assets will be stored ifenableDiskCache istrue. Must be read/write.

Default:<ContentRootPath>/obj/WebOptimizerCache

cdnUrl is an absolute URL that, if present, is automatically adds a prefix to any script, stylesheet or media file on the page. A Tag Helper adds the prefix automatically when the Tag Helpers have been registered. See how toregister the Tag Helpers here.

For example. if the cdnUrl is set to"http://my-cdn.com" then script and link tags will prepend thecdnUrl to the references. For instance, this script tag:

<scriptsrc="/js/file.js"></script>

...will become this:

<scriptsrc="http://my-cdn.com/js/file.js"></script>

allowEmptyBundle determines the behavior when there is no content in source file of a bundle, by default 404 exception will be thrown when the bundle is requested, set to true to get a bundle with empty content instead.

Default:false

Custom pipeline

Read more in thecustom pipeline documentation.

Extend

Extensions can hook up new transformations and consume existing ones.

A good extension to look at is theWebOptimizer.Sass extension. It demonstrates how to write a processor and how to write extension methods that makes it easy to hook it up to the pipeline.

Plugins

Releases

No releases published

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp