### Install and Configure WebOptimizer
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Add WebOptimizer services and middleware in Program.cs for automatic CSS and JS minification. Ensure UseWebOptimizer middleware is placed before UseStaticFiles.
```csharp
var builder = WebApplication.CreateBuilder(args);
// Add WebOptimizer services - enables automatic CSS and JS minification
builder.Services.AddWebOptimizer();
var app = builder.Build();
// Add WebOptimizer middleware BEFORE UseStaticFiles
app.UseWebOptimizer();
app.UseStaticFiles();
app.Run();
```
--------------------------------
### CDN URL Prefix Example
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Demonstrates how a CDN URL prefix is applied to script tags. This is automatically handled when the `cdnUrl` option is configured and Tag Helpers are registered.
```html
```
```html
```
--------------------------------
### Add Custom CSS Bundle with Optimizations
Source: https://github.com/ligershark/weboptimizer/wiki/Custom-pipeline
Use AddBundle to create a custom CSS bundle from text files. This example concatenates, fingerprints URLs, and minifies CSS. Ensure WebOptimizer is configured in services.
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddBundle("/bundle.css", "text/css; charset=utf-8", "/dir/*.txt")
.AdjustRelativePaths()
.Concatenate()
.FingerprintUrls()
.MinifyCss();
});
```
--------------------------------
### Cache Busted Link Tag
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Example of a link tag rendered by WebOptimizer with cache busting enabled. The 'v' parameter changes when source files are modified.
```html
```
--------------------------------
### Add WebOptimizer Services
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
In the ConfigureServices method of Startup.cs, add services.AddWebOptimizer() to register the necessary services.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddWebOptimizer(); // WebOptimizer
}
```
--------------------------------
### Configure WebOptimizer Options
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Configure caching, CDN, and bundling settings using either appsettings.json or the fluent C# API.
```json
// appsettings.json
{
"webOptimizer": {
"enableCaching": true,
"enableMemoryCache": true,
"enableDiskCache": true,
"cacheDirectory": "/var/cache/weboptimizer",
"enableTagHelperBundling": true,
"cdnUrl": "https://cdn.example.com/",
"allowEmptyBundle": false,
"httpsCompression": "Compress"
}
}
```
```csharp
// Or configure in code
services.AddWebOptimizer(pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "css/*.css");
},
options =>
{
options.EnableCaching = true; // Enable cache-control headers (default: true)
options.EnableMemoryCache = true; // Cache in IMemoryCache (default: true)
options.MemoryCacheTimeToLive = TimeSpan.FromHours(24);
options.EnableDiskCache = true; // Cache to disk (default: true in production)
options.CacheDirectory = "/var/cache"; // Disk cache location
options.EnableTagHelperBundling = true; // Enable Tag Helper bundling (default: true)
options.CdnUrl = "https://cdn.example.com/"; // Prepend to all asset URLs
options.AllowEmptyBundle = false; // Throw on empty bundles (default: false)
options.HttpsCompression = HttpsCompressionMode.Compress;
});
```
--------------------------------
### Configure WebOptimizer Middleware
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
In Startup.cs, add app.UseWebOptimizer() to the Configure method before app.UseStaticFiles().
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseWebOptimizer(); // WebOptimizer
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
```
--------------------------------
### Configure Minification in Startup
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Register specific JavaScript files for automatic minification within the WebOptimizer pipeline.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddWebOptimizer(pipeline =>
{
pipeline.MinifyJsFiles("js/a.js", "js/b.js", "js/c.js");
});
}
```
--------------------------------
### UseFileProvider
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Configures a bundle to use a custom `IFileProvider` for locating source files. Enables loading files from any location or custom file system.
```APIDOC
## UseFileProvider
### Description
Configures a bundle to use a custom `IFileProvider` for locating source files. Enables loading files from any location or custom file system.
### Method
Not Applicable (Configuration method)
### Endpoint
Not Applicable (Configuration method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
services.AddWebOptimizer(pipeline =>
{
// Use a custom physical file provider
var provider = new PhysicalFileProvider(@"C:\SharedAssets");
pipeline.AddJavaScriptBundle("/js/shared.js", "common.js", "utils.js")
.UseFileProvider(provider);
// Use embedded resources provider
var embeddedProvider = new EmbeddedFileProvider(typeof(MyClass).Assembly);
pipeline.AddCssBundle("/css/embedded.css", "Styles/theme.css")
.UseFileProvider(embeddedProvider);
});
```
### Response
#### Success Response (200)
Not Applicable (Configuration method)
#### Response Example
Not Applicable (Configuration method)
```
--------------------------------
### WebOptimizer Options Configuration
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Configure caching behavior, CDN URLs, and other options via appsettings.json or code.
```APIDOC
## WebOptimizerOptions Configuration
Configure caching behavior, CDN URLs, and other options via appsettings.json or code.
### Configuration via appsettings.json
```json
{
"webOptimizer": {
"enableCaching": true,
"enableMemoryCache": true,
"enableDiskCache": true,
"cacheDirectory": "/var/cache/weboptimizer",
"enableTagHelperBundling": true,
"cdnUrl": "https://cdn.example.com/",
"allowEmptyBundle": false,
"httpsCompression": "Compress"
}
}
```
### Configuration via Code
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "css/*.css");
},
options =>
{
options.EnableCaching = true; // Enable cache-control headers (default: true)
options.EnableMemoryCache = true; // Cache in IMemoryCache (default: true)
options.MemoryCacheTimeToLive = TimeSpan.FromHours(24);
options.EnableDiskCache = true; // Cache to disk (default: true in production)
options.CacheDirectory = "/var/cache"; // Disk cache location
options.EnableTagHelperBundling = true; // Enable Tag Helper bundling (default: true)
options.CdnUrl = "https://cdn.example.com/"; // Prepend to all asset URLs
options.AllowEmptyBundle = false; // Throw on empty bundles (default: false)
options.HttpsCompression = HttpsCompressionMode.Compress;
});
```
```
--------------------------------
### Configure WebOptimizer in Program.cs
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Sets up CSS and JavaScript bundles, enables minification, and configures global options like caching and CDN integration within an ASP.NET Core application.
```csharp
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddWebOptimizer(pipeline =>
{
// CSS bundles
pipeline.AddCssBundle("/css/site.css", "css/reset.css", "css/layout.css", "css/theme.css");
pipeline.AddCssBundle("/css/vendor.css", "node_modules/bootstrap/dist/css/bootstrap.css")
.UseContentRoot();
// JavaScript bundles with source maps for debugging
pipeline.AddJavaScriptBundle("/js/site.js",
new WebOptimizer.Processors.JsSettings { GenerateSourceMap = true },
"js/app.js", "js/components/*.js");
pipeline.AddJavaScriptBundle("/js/vendor.js",
"node_modules/jquery/dist/jquery.js",
"node_modules/bootstrap/dist/js/bootstrap.bundle.js")
.UseContentRoot();
// Auto-minify any CSS/JS not in bundles
pipeline.MinifyCssFiles();
pipeline.MinifyJsFiles();
},
options =>
{
options.EnableCaching = !builder.Environment.IsDevelopment();
options.EnableTagHelperBundling = !builder.Environment.IsDevelopment();
options.CdnUrl = builder.Configuration["CdnUrl"];
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseWebOptimizer();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();
```
--------------------------------
### Registering WebOptimizer Assets
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Configure WebOptimizer to process specified file types and paths. Ensure all required files are registered as assets.
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddFiles("text/javascript", "/dist/*");
pipeline.AddFiles("text/css", "/css/*");
});
```
--------------------------------
### Configure WebOptimizer Options in C#
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Configure WebOptimizer options programmatically in C# during application startup. This method allows for dynamic configuration and integration with dependency injection.
```csharp
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.EnableMemoryCache = true;
option.EnableDiskCache = true;
option.CacheDirectory = "/var/temp/weboptimizercache";
option.EnableTagHelperBundling = true;
option.CdnUrl = "https://my-cdn.com/";
option.AllowEmptyBundle = false;
option.HttpsCompression = HttpsCompressionMode.Compress;
});
```
--------------------------------
### Configure File Providers with UseFileProvider
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Enables loading files from custom locations or embedded resources using IFileProvider.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Use a custom physical file provider
var provider = new PhysicalFileProvider(@"C:\SharedAssets");
pipeline.AddJavaScriptBundle("/js/shared.js", "common.js", "utils.js")
.UseFileProvider(provider);
// Use embedded resources provider
var embeddedProvider = new EmbeddedFileProvider(typeof(MyClass).Assembly);
pipeline.AddCssBundle("/css/embedded.css", "Styles/theme.css")
.UseFileProvider(embeddedProvider);
});
```
--------------------------------
### Configure Content Root for Bundles
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Use UseContentRoot to resolve source files relative to the project root instead of wwwroot.
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "node_modules/jquery/dist/*.js")
.UseContentRoot();
});
```
--------------------------------
### Use Custom File Provider
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Specify a custom IFileProvider for locating bundle source files.
```csharp
services.AddWebOptimizer(pipeline =>
{
var provider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(@"C:\path\to\my\root\folder");
pipeline.AddJavaScriptBundle("/js/scripts.js", "a.js", "b.js")
.UseFileProvider(provider);
});
```
--------------------------------
### Enable Source Maps
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Configure JavaScript bundles to generate source maps during the build process.
```csharp
services.AddWebOptimizer(pipeline =>
{
. . .
pipeline.AddJavaScriptBundle("/js/scripts.js",
new WebOptimizer.Processors.JsSettings { GenerateSourceMap = true },
"a.js", "b.js");
});
```
--------------------------------
### Configure Content Root with UseContentRoot
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Sources files from the project root instead of the web root, useful for node_modules or external assets.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle files from node_modules (outside wwwroot)
pipeline.AddJavaScriptBundle("/js/vendor.js",
"node_modules/jquery/dist/jquery.js",
"node_modules/bootstrap/dist/js/bootstrap.js")
.UseContentRoot();
// Bundle CSS from content root
pipeline.AddCssBundle("/css/vendor.css",
"node_modules/bootstrap/dist/css/bootstrap.css")
.UseContentRoot();
});
```
--------------------------------
### UseContentRoot
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Configures a bundle to source files from the Content Root (project root) instead of the Web Root (wwwroot). Useful for bundling files from node_modules or other non-wwwroot locations.
```APIDOC
## UseContentRoot
### Description
Configures a bundle to source files from the Content Root (project root) instead of the Web Root (wwwroot). Useful for bundling files from node_modules or other non-wwwroot locations.
### Method
Not Applicable (Configuration method)
### Endpoint
Not Applicable (Configuration method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle files from node_modules (outside wwwroot)
pipeline.AddJavaScriptBundle("/js/vendor.js",
"node_modules/jquery/dist/jquery.js",
"node_modules/bootstrap/dist/js/bootstrap.js")
.UseContentRoot();
// Bundle CSS from content root
pipeline.AddCssBundle("/css/vendor.css",
"node_modules/bootstrap/dist/css/bootstrap.css")
.UseContentRoot();
});
```
### Response
#### Success Response (200)
Not Applicable (Configuration method)
#### Response Example
Not Applicable (Configuration method)
```
--------------------------------
### Configure WebOptimizer Services
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Register WebOptimizer services using AddWebOptimizer. Options include enabling automatic minification, controlling minification for development, or configuring custom bundles and pipeline options.
```csharp
// Option 1: Enable automatic minification (default behavior)
services.AddWebOptimizer();
```
```csharp
// Option 2: Control minification for development
services.AddWebOptimizer(minifyJavaScript: false, minifyCss: false);
```
```csharp
// Option 3: Configure pipeline with custom bundles
services.AddWebOptimizer(pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "css/a.css", "css/b.css");
pipeline.AddJavaScriptBundle("/js/bundle.js", "js/*.js");
});
```
```csharp
// Option 4: Configure both pipeline and options
services.AddWebOptimizer(
pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "css/*.css");
pipeline.MinifyJsFiles();
},
options =>
{
options.EnableCaching = true;
options.EnableMemoryCache = true;
options.EnableDiskCache = true;
options.CdnUrl = "https://my-cdn.com/";
});
```
--------------------------------
### Configure WebOptimizer Options in JSON
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Use this JSON structure in appsettings.json to configure WebOptimizer settings. Ensure the 'webOptimizer' key is present at the root or a relevant section.
```json
{
"webOptimizer": {
"enableCaching": true,
"enableMemoryCache": true,
"enableDiskCache": true,
"cacheDirectory": "/var/temp/weboptimizercache",
"enableTagHelperBundling": true,
"cdnUrl": "https://my-cdn.com/",
"allowEmptyBundle": false,
"httpsCompression": "Compress"
}
}
```
--------------------------------
### Create CSS Bundles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Use AddCssBundle to combine multiple CSS files into a single output. Supports specific files, glob patterns, and custom NUglify CSS settings. The output includes URL fingerprinting for cache busting.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle specific files
pipeline.AddCssBundle("/css/bundle.css", "css/site.css", "css/custom.css");
// Bundle using glob patterns
pipeline.AddCssBundle("/css/all.css", "css/**/*.css");
// Bundle with custom NUglify CSS settings
var cssSettings = new NUglify.Css.CssSettings
{
CommentMode = NUglify.Css.CssComment.None,
ColorNames = NUglify.Css.CssColor.Strict
};
pipeline.AddCssBundle("/css/styled.css", cssSettings, "css/theme.css", "css/layout.css");
});
// In your Razor view:
//
// Output:
```
--------------------------------
### Creating Custom Processors
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Extend WebOptimizer by creating custom processors that implement `IProcessor`. Processors transform asset content through the pipeline.
```APIDOC
## Creating Custom Processors
Extend WebOptimizer by creating custom processors that implement `IProcessor`. Processors transform asset content through the pipeline.
### Custom Processor Example
```csharp
// Custom processor that adds a header comment
public class PrependHeaderProcessor : Processor
{
private readonly string _header;
public PrependHeaderProcessor(string header)
{
_header = header;
}
public override Task ExecuteAsync(IAssetContext context)
{
var content = new Dictionary();
string header = $
```
--------------------------------
### Configure WebOptimizer Middleware
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Use the UseWebOptimizer middleware to intercept asset requests and serve transformed content. It must be placed before UseStaticFiles. Custom file provider options can also be configured.
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// WebOptimizer must come BEFORE UseStaticFiles
app.UseWebOptimizer();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapRazorPages());
}
```
```csharp
// Alternative: With custom file provider options
app.UseWebOptimizer(env, new FileProviderOptions []
{
new FileProviderOptions { RequestPath = "/lib", FileProvider = customProvider }
});
```
--------------------------------
### Create Custom Asset Processors
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Implement IProcessor to transform asset content and use extension methods to integrate them into the pipeline.
```csharp
// Custom processor that adds a header comment
public class PrependHeaderProcessor : Processor
{
private readonly string _header;
public PrependHeaderProcessor(string header)
{
_header = header;
}
public override Task ExecuteAsync(IAssetContext context)
{
var content = new Dictionary();
string header = $"/*\r\n {_header}\r\n*/";
foreach (string route in context.Content.Keys)
{
string updated = header + Environment.NewLine + context.Content[route].AsString();
content[route] = updated.AsByteArray();
}
context.Content = content;
return Task.CompletedTask;
}
}
// Extension method for fluent API
public static class CustomExtensions
{
public static IAsset PrependHeader(this IAsset asset, string header)
{
asset.Processors.Add(new PrependHeaderProcessor(header));
return asset;
}
public static IEnumerable PrependHeader(this IEnumerable assets, string header)
{
return assets.Select(a => a.PrependHeader(header)).ToList();
}
}
// Usage
services.AddWebOptimizer(pipeline =>
{
pipeline.AddJavaScriptBundle("/js/app.js", "js/*.js")
.PrependHeader("Copyright 2024 MyCompany")
.UseContentRoot();
});
```
--------------------------------
### Create CSS Bundles
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Combine multiple CSS files into a single minified bundle, or use globbing to include all files in a folder.
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "css/a.css", "css/b.css");
});
```
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddCssBundle("/css/bundle.css", "css/**/*.css");
});
```
--------------------------------
### Register Files with AddFiles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Registers multiple files with the pipeline without bundling them, allowing individual processing and serving.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Add JavaScript files for Tag Helper versioning
pipeline.AddFiles("text/javascript", "/dist/*.js");
// Add CSS files for cache busting
pipeline.AddFiles("text/css", "/css/*.css", "/themes/**/*.css");
// Chain with processors
pipeline.AddFiles("text/css; charset=UTF-8", "styles/*.css")
.FingerprintUrls()
.MinifyCss();
});
```
--------------------------------
### WebOptimizer Configuration Options
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Configuration options for WebOptimizer can be set in appsettings.json or directly in C# code. Below are the available options and their descriptions.
```APIDOC
## Configuration Options
WebOptimizer settings can be managed through `appsettings.json` or programmatically via C#.
### JSON Configuration Example
```json
{
"webOptimizer": {
"enableCaching": true,
"enableMemoryCache": true,
"enableDiskCache": true,
"cacheDirectory": "/var/temp/weboptimizercache",
"enableTagHelperBundling": true,
"cdnUrl": "https://my-cdn.com/",
"allowEmptyBundle": false,
"httpsCompression": "Compress"
}
}
```
### C# Configuration Example
```csharp
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.EnableMemoryCache = true;
option.EnableDiskCache = true;
option.CacheDirectory = "/var/temp/weboptimizercache";
option.EnableTagHelperBundling = true;
option.CdnUrl = "https://my-cdn.com/";
option.AllowEmptyBundle = false;
option.HttpsCompression = HttpsCompressionMode.Compress;
});
```
### Option Details
- **enableCaching** (boolean): Determines if `cache-control` HTTP headers are set and conditional GET (304) requests are supported. Useful to disable in development.
- Default: `true`
- **enableTagHelperBundling** (boolean): Determines if `` becomes ``.
- **allowEmptyBundle** (boolean): Determines behavior for empty source files in a bundle. If `false`, a 404 exception is thrown. If `true`, an empty bundle is returned.
- Default: `false`
- **httpsCompression** (string): Specifies the HTTPS compression mode. Possible values include `Compress`.
- Default: Not explicitly defined, but example shows `HttpsCompressionMode.Compress`.
```
--------------------------------
### Add WebOptimizer NuGet Package
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Use the dotnet CLI to add the WebOptimizer.Core NuGet package to your ASP.NET Core 2.0 project.
```cmd
dotnet add package LigerShark.WebOptimizer.Core
```
--------------------------------
### Add Custom Asset Bundles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Base method for creating custom asset bundles with full control over the transformation pipeline. Use for non-standard file types or custom processing chains. Supports specifying content types and applying transformations.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle text files as CSS
pipeline.AddBundle("/bundle.css", "text/css; charset=utf-8", "/dir/*.txt")
.AdjustRelativePaths()
.Concatenate()
.FingerprintUrls()
.MinifyCss();
// Bundle JSON files
pipeline.AddBundle("/config.json", "application/json", "config/*.json")
.Concatenate();
// Bundle with custom content type
pipeline.AddBundle("/data.xml", "application/xml", "data/*.xml")
.Concatenate();
});
```
--------------------------------
### Reference Bundles in HTML
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Update link tags to point to the generated bundle route.
```html
```
--------------------------------
### Add HTML Bundles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Combines multiple HTML files into a single output with automatic minification. Useful for bundling HTML templates or partials. Supports glob patterns.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle HTML templates
pipeline.AddHtmlBundle("/templates/all.html", "templates/*.html");
// Bundle with custom HTML settings
var htmlSettings = new NUglify.Html.HtmlSettings
{
RemoveComments = true,
CollapseWhitespaces = true
};
pipeline.AddHtmlBundle("/partials/bundle.html", htmlSettings,
"partials/header.html", "partials/footer.html");
});
```
--------------------------------
### Register Tag Helpers
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Add the WebOptimizer Tag Helpers to the _ViewImports.cshtml file.
```cshtml
@addTagHelper *, WebOptimizer.Core
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
```
--------------------------------
### Add JavaScript Bundles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Combines multiple JS files into a single output with automatic minification and optional source map generation. Supports glob patterns for file selection.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle specific files
pipeline.AddJavaScriptBundle("/js/bundle.js", "js/app.js", "js/utils.js");
// Bundle using glob patterns
pipeline.AddJavaScriptBundle("/js/all.js", "js/**/*.js");
// Bundle with source map generation for debugging
var jsSettings = new WebOptimizer.Processors.JsSettings
{
GenerateSourceMap = true
};
pipeline.AddJavaScriptBundle("/js/app.js", jsSettings, "js/module1.js", "js/module2.js");
// Source map available at: /js/app.map.js
// Bundle with custom NUglify code settings
var codeSettings = new NUglify.JavaScript.CodeSettings
{
PreserveImportantComments = false,
MinifyCode = true
};
pipeline.AddJavaScriptBundle("/js/vendor.js",
new WebOptimizer.Processors.JsSettings(codeSettings),
"js/jquery.js", "js/bootstrap.js");
});
```
--------------------------------
### Interact with IAssetPipeline
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Use the IAssetPipeline interface to register assets or retrieve them via dependency injection.
```csharp
public interface IAssetPipeline
{
IReadOnlyList Assets { get; }
IAsset AddBundle(string route, string contentType, params string[] sourceFiles);
IAsset AddBundle(IAsset asset);
IEnumerable AddBundle(IEnumerable assets);
IAsset AddAsset(string route, string contentType);
IEnumerable AddFiles(string contentType, params string[] sourceFiles);
bool TryGetAssetFromRoute(string route, out IAsset asset);
}
// Example: Accessing pipeline via DI
public class MyService
{
private readonly IAssetPipeline _pipeline;
public MyService(IAssetPipeline pipeline)
{
_pipeline = pipeline;
}
public void CheckAsset(string route)
{
if (_pipeline.TryGetAssetFromRoute(route, out IAsset asset))
{
Console.WriteLine($"Found asset: {asset.Route}");
Console.WriteLine($"Content-Type: {asset.ContentType}");
Console.WriteLine($"Source files: {string.Join(", ", asset.SourceFiles)}");
}
}
}
```
--------------------------------
### AddFiles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Registers multiple files with the pipeline without bundling them. Each file is processed individually and served at its original path.
```APIDOC
## AddFiles
### Description
Registers multiple files with the pipeline without bundling them. Each file is processed individually and served at its original path.
### Method
Not Applicable (Configuration method)
### Endpoint
Not Applicable (Configuration method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
services.AddWebOptimizer(pipeline =>
{
// Add JavaScript files for Tag Helper versioning
pipeline.AddFiles("text/javascript", "/dist/*.js");
// Add CSS files for cache busting
pipeline.AddFiles("text/css", "/css/*.css", "/themes/**/*.css");
// Chain with processors
pipeline.AddFiles("text/css; charset=UTF-8", "styles/*.css")
.FingerprintUrls()
.MinifyCss();
});
```
### Response
#### Success Response (200)
Not Applicable (Configuration method)
#### Response Example
Not Applicable (Configuration method)
```
--------------------------------
### Minify HTML with MinifyHtml
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Minifies HTML content using NUglify, automatically skipping files with .min.html extension.
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddBundle("/templates.html", "text/html", "templates/*.html")
.Concatenate()
.MinifyHtml();
// With custom settings
var settings = new NUglify.Html.HtmlSettings
{
RemoveComments = true,
RemoveQuotedAttributes = false
};
pipeline.AddBundle("/views.html", "text/html", "views/*.html")
.Concatenate()
.MinifyHtml(settings);
});
```
--------------------------------
### Minify CSS with MinifyCss
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Minifies CSS content using NUglify, automatically skipping files with .min.css extension.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Apply to single asset
pipeline.AddBundle("/styles.css", "text/css", "css/*.css")
.Concatenate()
.MinifyCss();
// Apply with custom settings
var settings = new NUglify.Css.CssSettings
{
CommentMode = NUglify.Css.CssComment.Hacks
};
pipeline.AddBundle("/theme.css", "text/css", "theme/*.css")
.Concatenate()
.MinifyCss(settings);
});
```
--------------------------------
### IAssetPipeline Interface
Source: https://context7.com/ligershark/weboptimizer/llms.txt
The core pipeline interface provides methods for registering assets and bundles. Access it via dependency injection or the configuration callback.
```APIDOC
## IAssetPipeline Interface
The core pipeline interface provides methods for registering assets and bundles. Access it via dependency injection or the configuration callback.
### Interface Definition
```csharp
public interface IAssetPipeline
{
IReadOnlyList Assets { get; }
IAsset AddBundle(string route, string contentType, params string[] sourceFiles);
IAsset AddBundle(IAsset asset);
IEnumerable AddBundle(IEnumerable assets);
IAsset AddAsset(string route, string contentType);
IEnumerable AddFiles(string contentType, params string[] sourceFiles);
bool TryGetAssetFromRoute(string route, out IAsset asset);
}
```
### Example Usage via Dependency Injection
```csharp
public class MyService
{
private readonly IAssetPipeline _pipeline;
public MyService(IAssetPipeline pipeline)
{
_pipeline = pipeline;
}
public void CheckAsset(string route)
{
if (_pipeline.TryGetAssetFromRoute(route, out IAsset asset))
{
Console.WriteLine($"Found asset: {asset.Route}");
Console.WriteLine($"Content-Type: {asset.ContentType}");
Console.WriteLine($"Source files: {string.Join(", ", asset.SourceFiles)}");
}
}
}
```
```
--------------------------------
### MinifyCss
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Processor that minifies CSS content using NUglify. Automatically skips files with `.min.css` extension.
```APIDOC
## MinifyCss
### Description
Processor that minifies CSS content using NUglify. Automatically skips files with `.min.css` extension.
### Method
Not Applicable (Configuration method)
### Endpoint
Not Applicable (Configuration method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
services.AddWebOptimizer(pipeline =>
{
// Apply to single asset
pipeline.AddBundle("/styles.css", "text/css", "css/*.css")
.Concatenate()
.MinifyCss();
// Apply with custom settings
var settings = new NUglify.Css.CssSettings
{
CommentMode = NUglify.Css.CssComment.Hacks
};
pipeline.AddBundle("/theme.css", "text/css", "theme/*.css")
.Concatenate()
.MinifyCss(settings);
});
```
### Response
#### Success Response (200)
Not Applicable (Configuration method)
#### Response Example
Not Applicable (Configuration method)
```
--------------------------------
### Configuring Response Compression for text/javascript
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Add 'text/javascript' to MimeTypes for response compression when using WebOptimizer with older ASP.NET Core versions. Ensure 'app.UseResponseCompression()' is called before 'app.UseWebOptimizer()'.
```csharp
services.AddResponseCompression( options => {
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "text/javascript"}
);
});
```
--------------------------------
### AddHtmlBundle
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Creates an HTML bundle that combines multiple HTML files with automatic minification. Useful for bundling HTML templates or partials.
```APIDOC
## AddHtmlBundle
### Description
Creates an HTML bundle that combines multiple HTML files with automatic minification. Useful for bundling HTML templates or partials.
### Method
Not Applicable (Configuration via C#)
### Endpoint
Not Applicable (Configuration via C#)
### Parameters
Not Applicable (Configuration via C#)
### Request Example
Not Applicable (Configuration via C#)
### Response
Not Applicable (Configuration via C#)
## Usage Examples:
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle HTML templates
pipeline.AddHtmlBundle("/templates/all.html", "templates/*.html");
// Bundle with custom HTML settings
var htmlSettings = new NUglify.Html.HtmlSettings
{
RemoveComments = true,
CollapseWhitespaces = true
};
pipeline.AddHtmlBundle("/partials/bundle.html", htmlSettings,
"partials/header.html", "partials/footer.html");
});
```
```
--------------------------------
### Cache Busting Tag Helpers
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Automatically append version hashes to asset URLs by registering Tag Helpers in _ViewImports.cshtml.
```cshtml
@* _ViewImports.cshtml *@
@addTagHelper *, WebOptimizer.Core
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@* Usage in Razor views - version hash is added automatically *@
@* Output: *@
@* Output: *@
@* CDN URL is prepended if configured *@
@* With CdnUrl = "https://cdn.example.com" *@
@* Output: *@
```
--------------------------------
### MinifyCssFiles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Automatically minifies CSS files on request without bundling them. Files are served at their original paths but with minified content.
```APIDOC
## MinifyCssFiles
### Description
Automatically minifies CSS files on request without bundling them. Files are served at their original paths but with minified content.
### Method
Not Applicable (Configuration via C#)
### Endpoint
Not Applicable (Configuration via C#)
### Parameters
Not Applicable (Configuration via C#)
### Request Example
`GET /css/site.css`
### Response
Minified CSS content with cache headers
## Usage Examples:
```csharp
services.AddWebOptimizer(pipeline =>
{
// Minify all CSS files in the project
pipeline.MinifyCssFiles();
// Minify specific CSS files
pipeline.MinifyCssFiles("css/site.css", "css/admin.css");
// Minify with glob patterns
pipeline.MinifyCssFiles("css/**/*.css");
// Minify with custom settings
var settings = new NUglify.Css.CssSettings
{
TermSemicolons = true
};
pipeline.MinifyCssFiles(settings, "css/theme.css");
});
```
```
--------------------------------
### MinifyHtml
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Processor that minifies HTML content using NUglify. Automatically skips files with `.min.html` extension.
```APIDOC
## MinifyHtml
### Description
Processor that minifies HTML content using NUglify. Automatically skips files with `.min.html` extension.
### Method
Not Applicable (Configuration method)
### Endpoint
Not Applicable (Configuration method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
services.AddWebOptimizer(pipeline =>
{
pipeline.AddBundle("/templates.html", "text/html", "templates/*.html")
.Concatenate()
.MinifyHtml();
// With custom settings
var settings = new NUglify.Html.HtmlSettings
{
RemoveComments = true,
RemoveQuotedAttributes = false
};
pipeline.AddBundle("/views.html", "text/html", "views/*.html")
.Concatenate()
.MinifyHtml(settings);
});
```
### Response
#### Success Response (200)
Not Applicable (Configuration method)
#### Response Example
Not Applicable (Configuration method)
```
--------------------------------
### Minify JavaScript with MinifyJavaScript
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Minifies JavaScript content using NUglify, automatically skipping files with .min.js extension.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Apply to single asset
pipeline.AddBundle("/app.js", "text/javascript", "js/*.js")
.Concatenate()
.MinifyJavaScript();
// Apply with custom settings for source maps
var settings = new WebOptimizer.Processors.JsSettings
{
GenerateSourceMap = true,
CodeSettings = new NUglify.JavaScript.CodeSettings
{
PreserveImportantComments = true
}
};
pipeline.AddBundle("/debug.js", "text/javascript", "js/*.js")
.Concatenate()
.MinifyJavaScript(settings);
});
```
--------------------------------
### Concatenate Files with Concatenate
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Combines multiple source files into a single output file.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Manual pipeline with concatenation
pipeline.AddBundle("/combined.txt", "text/plain", "files/*.txt")
.Concatenate();
// Concatenate is automatically included in AddCssBundle and AddJavaScriptBundle
});
```
--------------------------------
### Fingerprint URLs with FingerprintUrls
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Adds cache-busting version hashes to CSS url() references.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Fingerprint URL references in CSS
pipeline.AddBundle("/styles.css", "text/css", "css/*.css")
.AdjustRelativePaths()
.FingerprintUrls() // Add before Concatenate
.Concatenate()
.MinifyCss();
});
```
--------------------------------
### MinifyJavaScript
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Processor that minifies JavaScript content using NUglify. Automatically skips files with `.min.js` extension.
```APIDOC
## MinifyJavaScript
### Description
Processor that minifies JavaScript content using NUglify. Automatically skips files with `.min.js` extension.
### Method
Not Applicable (Configuration method)
### Endpoint
Not Applicable (Configuration method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
services.AddWebOptimizer(pipeline =>
{
// Apply to single asset
pipeline.AddBundle("/app.js", "text/javascript", "js/*.js")
.Concatenate()
.MinifyJavaScript();
// Apply with custom settings for source maps
var settings = new WebOptimizer.Processors.JsSettings
{
GenerateSourceMap = true,
CodeSettings = new NUglify.JavaScript.CodeSettings
{
PreserveImportantComments = true
}
};
pipeline.AddBundle("/debug.js", "text/javascript", "js/*.js")
.Concatenate()
.MinifyJavaScript(settings);
});
```
### Response
#### Success Response (200)
Not Applicable (Configuration method)
#### Response Example
Not Applicable (Configuration method)
```
--------------------------------
### MinifyJsFiles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Automatically minifies JavaScript files on request without bundling them. Files are served at their original paths but with minified content.
```APIDOC
## MinifyJsFiles
### Description
Automatically minifies JavaScript files on request without bundling them. Files are served at their original paths but with minified content.
### Method
Not Applicable (Configuration via C#)
### Endpoint
Not Applicable (Configuration via C#)
### Parameters
Not Applicable (Configuration via C#)
### Request Example
Not Applicable (Configuration via C#)
### Response
Minified JavaScript content with cache headers
## Usage Examples:
```csharp
services.AddWebOptimizer(pipeline =>
{
// Minify all JS files in the project
pipeline.MinifyJsFiles();
// Minify specific JS files
pipeline.MinifyJsFiles("js/app.js", "js/helpers.js");
// Minify with glob patterns
pipeline.MinifyJsFiles("js/**/*.js");
// Minify with custom code settings
var codeSettings = new NUglify.JavaScript.CodeSettings
{
LocalRenaming = NUglify.JavaScript.LocalRenaming.KeepAll
};
pipeline.MinifyJsFiles(codeSettings);
});
// Note: Files ending with .min.js are automatically skipped
```
```
--------------------------------
### AddJavaScriptBundle
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Creates a JavaScript bundle that combines multiple JS files into a single output file with automatic minification. Supports source map generation for debugging.
```APIDOC
## AddJavaScriptBundle
### Description
Creates a JavaScript bundle that combines multiple JS files into a single output file with automatic minification. Supports source map generation for debugging.
### Method
Not Applicable (Configuration via C#)
### Endpoint
Not Applicable (Configuration via C#)
### Parameters
Not Applicable (Configuration via C#)
### Request Example
Not Applicable (Configuration via C#)
### Response
Not Applicable (Configuration via C#)
## Usage Examples:
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle specific files
pipeline.AddJavaScriptBundle("/js/bundle.js", "js/app.js", "js/utils.js");
// Bundle using glob patterns
pipeline.AddJavaScriptBundle("/js/all.js", "js/**/*.js");
// Bundle with source map generation for debugging
var jsSettings = new WebOptimizer.Processors.JsSettings
{
GenerateSourceMap = true
};
pipeline.AddJavaScriptBundle("/js/app.js", jsSettings, "js/module1.js", "js/module2.js");
// Source map available at: /js/app.map.js
// Bundle with custom NUglify code settings
var codeSettings = new NUglify.JavaScript.CodeSettings
{
PreserveImportantComments = false,
MinifyCode = true
};
pipeline.AddJavaScriptBundle("/js/vendor.js",
new WebOptimizer.Processors.JsSettings(codeSettings),
"js/jquery.js", "js/bootstrap.js");
});
```
```
--------------------------------
### AddBundle (Custom Pipeline)
Source: https://context7.com/ligershark/weboptimizer/llms.txt
The base method for creating custom asset bundles with full control over the transformation pipeline. Use this for non-standard file types or custom processing chains.
```APIDOC
## AddBundle (Custom Pipeline)
### Description
The base method for creating custom asset bundles with full control over the transformation pipeline. Use this for non-standard file types or custom processing chains.
### Method
Not Applicable (Configuration via C#)
### Endpoint
Not Applicable (Configuration via C#)
### Parameters
Not Applicable (Configuration via C#)
### Request Example
Not Applicable (Configuration via C#)
### Response
Not Applicable (Configuration via C#)
## Usage Examples:
```csharp
services.AddWebOptimizer(pipeline =>
{
// Bundle text files as CSS
pipeline.AddBundle("/bundle.css", "text/css; charset=utf-8", "/dir/*.txt")
.AdjustRelativePaths()
.Concatenate()
.FingerprintUrls()
.MinifyCss();
// Bundle JSON files
pipeline.AddBundle("/config.json", "application/json", "config/*.json")
.Concatenate();
// Bundle with custom content type
pipeline.AddBundle("/data.xml", "application/xml", "data/*.xml")
.Concatenate();
});
```
```
--------------------------------
### MinifyHtmlFiles
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Automatically minifies HTML files on request. Removes unnecessary whitespace and comments while preserving document structure.
```APIDOC
## MinifyHtmlFiles
### Description
Automatically minifies HTML files on request. Removes unnecessary whitespace and comments while preserving document structure.
### Method
Not Applicable (Configuration via C#)
### Endpoint
Not Applicable (Configuration via C#)
### Parameters
Not Applicable (Configuration via C#)
### Request Example
Not Applicable (Configuration via C#)
### Response
Minified HTML content with cache headers
## Usage Examples:
```csharp
services.AddWebOptimizer(pipeline =>
{
// Minify all HTML files
pipeline.MinifyHtmlFiles();
// Minify specific files
pipeline.MinifyHtmlFiles("views/*.html", "templates/**/*.html");
// Minify with custom settings
var htmlSettings = new NUglify.Html.HtmlSettings
{
RemoveOptionalTags = false,
ShortBooleanAttribute = true
};
pipeline.MinifyHtmlFiles(htmlSettings, "pages/*.html");
});
```
```
--------------------------------
### Minify CSS Files
Source: https://context7.com/ligershark/weboptimizer/llms.txt
Automatically minifies CSS files on request without bundling. Files are served at their original paths with minified content. Supports glob patterns and custom settings.
```csharp
services.AddWebOptimizer(pipeline =>
{
// Minify all CSS files in the project
pipeline.MinifyCssFiles();
// Minify specific CSS files
pipeline.MinifyCssFiles("css/site.css", "css/admin.css");
// Minify with glob patterns
pipeline.MinifyCssFiles("css/**/*.css");
// Minify with custom settings
var settings = new NUglify.Css.CssSettings
{
TermSemicolons = true
};
pipeline.MinifyCssFiles(settings, "css/theme.css");
});
// Request: GET /css/site.css
// Response: Minified CSS content with cache headers
```
--------------------------------
### Minify CSS with Globbing
Source: https://github.com/ligershark/weboptimizer/blob/master/README.md
Apply minification to all CSS files within a directory structure using globbing patterns.
```csharp
pipeline.MinifyCssFiles("css/**/*.css");
```