### Minify HTML with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Demonstrates basic and advanced HTML minification using NUglify. The advanced example shows how to configure settings like comment removal, whitespace collapsing, and minification of embedded CSS/JS.
```csharp
using NUglify;
using NUglify.Html;
var htmlResult = Uglify.Html(@"
\n
This is some text with spaces
\n \n
");
Console.WriteLine(htmlResult.Code);
var htmlSettings = new HtmlSettings
{
RemoveComments = true,
CollapseWhitespaces = true,
RemoveOptionalTags = true,
RemoveAttributeQuotes = true,
RemoveEmptyAttributes = true,
DecodeEntityCharacters = true,
ShortBooleanAttribute = true,
MinifyJs = true,
MinifyCss = true,
RemoveScriptStyleTypeAttribute = true
};
var minifiedHtml = Uglify.Html(fullHtml, htmlSettings);
Console.WriteLine(minifiedHtml.Code);
```
--------------------------------
### JavaScript Resource Usage Example
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Shows how to reference a virtual global object in JavaScript source code that will be replaced by the minifier. The minifier substitutes these properties with values defined in the RESX file.
```javascript
document.write("
" + Strings.Greeting + "
");
alert(Strings.Praise);
```
--------------------------------
### Generate JavaScript Source Maps with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Illustrates how to generate source maps for minified JavaScript using NUglify's V3SourceMap class. This allows debugging minified code by mapping it back to the original source. The example shows creating a source map, configuring settings to include it, minifying the JavaScript, and outputting the source map JSON and minified code.
```csharp
using NUglify;
using NUglify.JavaScript;
using System.IO;
// Create a source map
var sourceMap = new V3SourceMap();
sourceMap.StartPackage("output.js", "output.js.map");
var settings = new CodeSettings
{
MinifyCode = true,
SymbolsMap = sourceMap,
SourceMode = JavaScriptSourceMode.Program
};
var originalJs = @"
function greet(name) {
var message = 'Hello, ' + name;
console.log(message);
return message;
}
greet('World');
";
var result = Uglify.Js(originalJs, "source.js", settings);
// End the source map and get the JSON
using (var writer = new StringWriter())
{
sourceMap.EndFile(writer, "\n");
sourceMap.EndPackage();
var sourceMapJson = sourceMap.ToString();
Console.WriteLine("Source Map:");
Console.WriteLine(sourceMapJson);
}
Console.WriteLine("\nMinified JS:");
Console.WriteLine(result.Code);
// Add source map reference to output
var outputWithSourceMap = result.Code + "\n//# sourceMappingURL=output.js.map";
```
--------------------------------
### HTML5 Keygen Tag Example
Source: https://github.com/trullock/nuglify/blob/master/src/NUglify.Tests/TestData/HTML/tidy-html5-tests/html5/keygen.org.html
This snippet demonstrates the basic structure of the HTML5 keygen tag. It includes fields for username and encryption, and a note about browser support.
```html
```
--------------------------------
### Analyzing Function Scope and Variable Renaming
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This is an example of the analytical output from Microsoft Ajax Minifier, showing function scope details. It lists the function name, its starting line number, and details about arguments and local variables, including their original names and any names they were renamed to during minification. This aids in debugging and understanding code transformations.
```text
Function AddForecastCallback - starts at line 2233 (renamed to s)
context [argument] (renamed to k)
response [argument] (renamed to g)
cities [local var] (renamed to f)
```
--------------------------------
### NUglify Merging Localized Resource Files (RESX)
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
NUglify supports merging RESX string resource files into JavaScript and CSS at build time for localization. This example shows how to use 'Greeting' and 'Praise' strings from a 'strings.resx' file.
```javascript
document.write(NUglify.Resources.strings.Greeting);
alert(NUglify.Resources.strings.Praise);
```
--------------------------------
### HTML Example with Big Tag
Source: https://github.com/trullock/nuglify/blob/master/src/NUglify.Tests/TestData/HTML/tidy-html5-tests/html5/html4/big5.html
Demonstrates the usage of the 'big' CSS class within an HTML tag to render larger text. This is a common pattern for highlighting specific text elements.
```html
bigger text
```
--------------------------------
### Localized JavaScript Output with Unicode Escaping
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Example of the resulting JavaScript output after minification with a localized RESX file, showing how non-ASCII characters are escaped for compatibility.
```javascript
document.write("
\\u4f60\\u597d\\uff01
");alert("\\u771f\\u68d2\\uff01")
```
--------------------------------
### Specifying External Globals with Ajax Minifier
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This command-line example demonstrates how to use the --global option with Microsoft Ajax Minifier to specify known external global variables, preventing 'undefined global' warnings for variables defined in other modules.
```bash
ajaxmin –analyze inputfile.js –global:XMLSerializer,Msn,HelperFunction
```
--------------------------------
### Combine Duplicate Literals Optimization
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Shows an example of how the CombineDuplicateLiterals setting transforms repetitive code into a more compact form using local variables.
```javascript
function foo(a)
{
a.b = 12345;
a.c = 12345;
a.d = 12345;
a.e = 12345;
}
// Becomes:
function foo(a)
{
var b = 12345;
a.b = b;
a.c = b;
a.d = b;
a.e = b
}
```
--------------------------------
### Conditional Compilation Comments
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Example of using @cc_on for conditional compilation, which NUglify supports at the statement level.
```javascript
var ie = false;
/*@cc_on
ie = true;
@*/
alert(ie ? "Internet Explorer" : "NOT Internet Explorer");
```
--------------------------------
### Example of Localization Variable Usage
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This JavaScript snippet illustrates the practice of prefixing variable names with 'L_' for strings that need to be localized. This convention allows localization tools to easily identify and manage translatable text.
```javascript
var L_hello_text = "Hello there! ";
alert(L_hello_text);
```
--------------------------------
### Compile RESX Resources into JavaScript
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates the command-line usage for mapping a global object to a RESX file during the minification process. This replaces property references in JavaScript with actual string literals from the resource file.
```bash
ajaxmin foo.js –RES:Strings strings.resx
```
--------------------------------
### Configure HTML minification settings
Source: https://github.com/trullock/nuglify/blob/master/readme.md
Shows how to customize HTML minification output by using the HtmlSettings class, specifically for setting indentation.
```csharp
var htmlSettings = HtmlSettings.Pretty();
htmlSettings.Indent = "\t";
var output = Uglify.Html(input, htmlSettings);
```
--------------------------------
### Minify JavaScript with Default Settings
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates how to minify JavaScript code using the default settings of the MinifyJavaScript method from the Microsoft.Ajax.Utilities.Minifier object.
```APIDOC
## Minify JavaScript (Default)
### Description
Minifies JavaScript code using default settings.
### Method
```csharp
public string MinifyJavaScript(string source);
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **source** (string) - Required - The JavaScript code to minify.
### Request Example
```csharp
var minifier = new Microsoft.Ajax.Utilities.Minifier();
string minifiedCode = minifier.MinifyJavaScript("function() { console.log('hello world'); }");
```
### Response
#### Success Response (200)
- **minifiedCode** (string) - The minified JavaScript code.
#### Response Example
```javascript
function(){console.log("hello world")}
```
```
--------------------------------
### Configure CSS Minification Settings with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Illustrates how to configure CSS minification settings using NUglify. This includes options for color optimization, comment preservation, code optimization, browser compatibility, and output formatting.
```csharp
using NUglify;
using NUglify.Css;
var settings = new CssSettings
{
// Color optimization
ColorNames = CssColor.Strict, // Use W3C strict color names only
AbbreviateHexColor = true, // #ffffff -> #fff
// Comment handling
CommentMode = CssComment.Important, // Keep /*! important */ comments
// Code optimization
MinifyExpressions = true, // Minify calc() expressions
RemoveEmptyBlocks = true, // Remove rules with no declarations
DecodeEscapes = true, // Decode unicode escapes
// Browser compatibility
FixIE8Fonts = true, // Fix IE8 .EOT font URLs
// Output formatting
OutputMode = OutputMode.SingleLine,
TermSemicolons = false,
// Vendor prefix filtering (remove specific prefixes)
// ExcludeVendorPrefixes = { "ms", "webkit" }
};
var css = @"
/*! Theme styles */
.button {
background-color: #FF0000;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.empty-rule { }
";
var result = Uglify.Css(css, "theme.css", settings);
Console.WriteLine(result.Code);
```
--------------------------------
### Minify JavaScript with Custom Settings
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Shows how to minify JavaScript code with custom configurations using the CodeSettings object.
```APIDOC
## Minify JavaScript (Custom Settings)
### Description
Minifies JavaScript code using custom settings defined in a CodeSettings object.
### Method
```csharp
public string MinifyJavaScript(string source, CodeSettings settings);
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **source** (string) - Required - The JavaScript code to minify.
- **settings** (CodeSettings) - Optional - An object containing custom minification settings.
### Request Example
```csharp
var minifier = new Microsoft.Ajax.Utilities.Minifier();
var settings = new Microsoft.Ajax.Utilities.CodeSettings
{
OutputMode = Microsoft.Ajax.Utilities.OutputMode.MultipleLines,
IndentSize = 2,
LocalRenaming = Microsoft.Ajax.Utilities.LocalRenaming.CrunchAll
};
string minifiedCode = minifier.MinifyJavaScript("function() { var message = 'hello world'; console.log(message); }", settings);
```
### Response
#### Success Response (200)
- **minifiedCode** (string) - The minified JavaScript code.
#### Response Example
```javascript
function(){
var a=message;
console.log(a)
}
```
```
--------------------------------
### Handling Ambiguous Try/Catch Variables in JavaScript
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates a cross-browser issue where the 'catch' block variable scope differs between Internet Explorer and other browsers. This example highlights how IE can cause variable name collisions.
```javascript
var a, e = 10;
try
{
// force an error
a = foo;
}
catch (e)
{
// error handling
}
alert(e);
```
--------------------------------
### Basic Minification with NUglify
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This command demonstrates the most basic usage of NUglify to minify a JavaScript file. The output will be sent to the standard output stream.
```bash
ajaxmin inputfile.js
```
--------------------------------
### Configure HTML Minification Settings with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Demonstrates how to configure HtmlSettings for comprehensive HTML minification in NUglify. This includes options for whitespace, tag/attribute optimization, comment handling, embedded script/style minification, and parsing behavior. It also shows how to customize embedded JS and CSS settings and selectively keep/remove tags and attributes.
```csharp
using NUglify;
using NUglify.Html;
using NUglify.JavaScript;
using NUglify.Css;
var settings = new HtmlSettings
{
// Whitespace handling
CollapseWhitespaces = true,
KeepOneSpaceWhenCollapsing = false,
// Tag optimization
RemoveOptionalTags = true, // Remove , , etc.
RemoveInvalidClosingTags = true,
// Attribute optimization
RemoveEmptyAttributes = true,
RemoveAttributeQuotes = true, // Remove quotes when safe
ShortBooleanAttribute = true, // disabled="disabled" -> disabled
DecodeEntityCharacters = true, // & -> &
AlphabeticallyOrderAttributes = false,
// Comment handling
RemoveComments = true,
// KeepCommentsRegex can preserve specific comments
// Script/Style handling
RemoveScriptStyleTypeAttribute = true, // Remove type="text/javascript"
MinifyJs = true,
MinifyJsAttributes = true, // Minify onclick, etc.
MinifyCss = true,
MinifyCssAttributes = true, // Minify style attributes
RemoveJavaScript = false, // Set true to strip all JS
// Parsing options
IsFragmentOnly = false, // True for HTML fragments
TagsCaseSensitive = false,
AttributesCaseSensitive = false,
// Pretty print (for readable output)
PrettyPrint = false,
Indent = " ",
OutputTextNodesOnNewLine = true
};
// Configure embedded JS settings
settings.JsSettings = new CodeSettings
{
MinifyCode = true,
LocalRenaming = LocalRenaming.CrunchAll
};
// Configure embedded CSS settings
settings.CssSettings = new CssSettings
{
ColorNames = CssColor.Strict,
RemoveEmptyBlocks = true
};
// Selectively keep certain optional tags
settings.KeepTags.Add("tbody");
// Remove specific attributes from all elements
settings.RemoveAttributes.Add("data-debug");
var html = @"
Hello & welcome
";
var result = Uglify.Html(html, settings);
Console.WriteLine(result.Code);
// Output:
Hello & welcome
```
--------------------------------
### Preserving Localization Variable Names
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This command uses the -RENAME:localization option to keep variable names that start with 'L_' intact. This is crucial for applications that use a localization scheme where these variables hold translatable strings.
```bash
ajaxmin –rename:localization inputfile.js –out outputfile.js
```
--------------------------------
### Pretty Print JavaScript with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Uses CodeSettings to format minified JavaScript into a readable, multi-line structure.
```csharp
using NUglify;
using NUglify.JavaScript;
var prettySettings = CodeSettings.Pretty();
var prettyResult = Uglify.Js(minifiedJs, "script.js", prettySettings);
Console.WriteLine(prettyResult.Code);
```
--------------------------------
### CLI -RES Option for JavaScript
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Explains how to use the -RES switch to inject localized strings from a RESX file into JavaScript source code.
```APIDOC
## CLI -RES: JavaScript Localization
### Description
This command maps a RESX file to a virtual global object in JavaScript. During minification, references to this object's properties are replaced with the corresponding string literals from the RESX file.
### Method
CLI Command
### Endpoint
ajaxmin [input_file] -RES:[global_object] [path_to_resx]
### Parameters
#### Path Parameters
- **input_file** (string) - Required - The source JavaScript file to be minified.
#### Query Parameters
- **global_object** (string) - Required - The name of the virtual object used in the JS code.
- **path_to_resx** (string) - Required - The file path to the .resx resource file.
### Request Example
ajaxmin foo.js -RES:Strings strings.resx
### Response
#### Success Response (Output)
- **Result** (string) - Minified JavaScript with property references replaced by localized string literals.
```
--------------------------------
### Configure JavaScript Minification Settings with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Demonstrates comprehensive settings for JavaScript minification using NUglify. This includes options for variable renaming, code removal, output formatting, and handling of debug statements and specific JavaScript quirks.
```csharp
using NUglify;
using NUglify.JavaScript;
var settings = new CodeSettings
{
// Minification controls
MinifyCode = true, // Enable all minification
LocalRenaming = LocalRenaming.CrunchAll, // Rename all local variables
RemoveUnneededCode = true, // Remove unreachable code
RemoveFunctionExpressionNames = true, // Remove unused function names
CollapseToLiteral = true, // Convert new Object() to {}
EvalLiteralExpressions = true, // Evaluate constant expressions
// Debug handling
StripDebugStatements = true, // Remove debugger statements
// Safety settings
EvalTreatment = EvalTreatment.Ignore, // How to handle eval()
MacSafariQuirks = true, // Add Safari compatibility
InlineSafeStrings = true, // Break up in strings
// Output settings
OutputMode = OutputMode.SingleLine, // Single line output
PreserveImportantComments = true, // Keep /*! */ comments
TermSemicolons = false, // Don't add trailing semicolons
// Known globals (suppress undefined warnings)
KnownGlobalNamesList = "jQuery,$,React",
// Prevent renaming specific identifiers
NoAutoRenameList = "$super,exports"
};
var jsCode = @"
/*! License: MIT */
function processData(inputData) {
var result = new Object();
result.value = inputData * 2;
debugger;
return result;
}
";
var result = Uglify.Js(jsCode, settings);
Console.WriteLine(result.Code);
```
--------------------------------
### JavaScript Function-Level Scope vs. Block-Level Scope
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This example illustrates the difference between JavaScript's function-level scope and block-level scopes found in languages like C# or C++. In JavaScript, redeclaring a variable within a loop (like 'a' in this case) reuses the existing variable, potentially leading to unexpected results. Microsoft Ajax Minifier flags variables defined multiple times within the same scope.
```javascript
function func()
{
var n, a = "outer";
for (n = 0; n < 10; ++n)
{
var a = n;
// do something else
}
alert(a);
}
```
--------------------------------
### Pretty Print HTML with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Configures HTML settings to produce human-readable, indented output instead of minified code. This is useful for debugging purposes.
```csharp
using NUglify;
using NUglify.Html;
var htmlSettings = HtmlSettings.Pretty();
htmlSettings.Indent = "\t";
var prettyResult = Uglify.Html(uglyHtml, htmlSettings);
Console.WriteLine(prettyResult.Code);
```
--------------------------------
### CssSettings.Pretty - Pretty Print CSS
Source: https://context7.com/trullock/nuglify/llms.txt
Configures NUglify to output CSS in a readable, formatted, multi-line style while preserving all comments.
```APIDOC
## CssSettings.Pretty - Pretty Print CSS
### Description
Returns CSS settings configured for readable, formatted output. Preserves all comments and outputs on multiple lines.
### Method
N/A (This is a static settings configuration)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```csharp
using NUglify;
using NUglify.Css;
var prettyCssSettings = CssSettings.Pretty();
// Settings: CommentMode = All, MinifyExpressions = false, OutputMode = MultipleLines
var minifiedCss = ".btn{color:red;padding:10px}.container{margin:0 auto;max-width:1200px}";
var prettyCss = Uglify.Css(minifiedCss, "styles.css", prettyCssSettings);
Console.WriteLine(prettyCss.Code);
```
### Response
#### Success Response (200)
N/A (This is a settings configuration, not an endpoint)
#### Response Example
```css
.btn {
color: red;
padding: 10px;
}
.container {
margin: 0 auto;
max-width: 1200px;
}
```
```
--------------------------------
### Minification with Output File Redirection
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This command shows how to specify an output file for the minified code using the -OUT option. If the output file already exists, an error will be thrown by default.
```bash
ajaxmin inputfile.js –out outputfile.js
```
--------------------------------
### CLI -RES Option for CSS
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Explains how to use the -RES switch to localize CSS property values using specially formatted comments.
```APIDOC
## CLI -RES: CSS Localization
### Description
For CSS, the -RES switch allows replacing property values with localized strings from a RESX file by placing a comment `/*[id]*/` before the property.
### Method
CLI Command
### Endpoint
ajaxmin [input_file] -RES:[path_to_resx]
### Parameters
#### Path Parameters
- **input_file** (string) - Required - The source CSS file.
- **path_to_resx** (string) - Required - The file path to the .resx resource file.
### Request Example
body { /*[BodyFontFamily]*/ font-family: Arial; }
### Response
#### Success Response (Output)
- **Result** (string) - CSS with property values updated based on the matching ID in the RESX file.
```
--------------------------------
### Pretty Print Option
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Explains the use of the -PRETTY option for generating readable, multi-line output.
```APIDOC
## Pretty Print Option
### Description
The `-PRETTY` option formats minified code into an easy-to-read, multi-line format, which is highly recommended for debugging.
### Usage
- **Command Line**: Use the `-PRETTY` switch. To specify a custom indent size (e.g., 2 spaces), use `-PRETTY:2`.
- **DLL API**: Control this via the `OutputMode` and `IndentSize` properties on the `CodeSettings` object.
### Behavior
- When used with JavaScript, `-PRETTY` turns off local variable and function renaming unless `-RENAME` is also specified.
- Works for both JavaScript and CSS.
- `IndentSize` property in `CodeSettings` corresponds to the numeric value after the colon in the command-line switch.
```
--------------------------------
### Minify JavaScript using DLL API
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates the method signatures for the Minifier object to process JavaScript source code with optional custom settings.
```csharp
public string MinifyJavaScript(string source);
public string MinifyJavaScript(string source, CodeSettings settings);
```
--------------------------------
### Handle Minification Results with UglifyResult
Source: https://context7.com/trullock/nuglify/llms.txt
Explains how to use the UglifyResult object to access minified code, check for errors, and process warnings. It demonstrates iterating through errors and warnings, retrieving the minified code as a string, and implicit conversion to string.
```csharp
using NUglify;
using NUglify.JavaScript;
var jsWithErrors = @"
function test() {
var x = 1
var x = 2; // Duplicate variable
return x
}
";
var settings = new CodeSettings
{
MinifyCode = true,
WarningLevel = 4 // Show all warnings
};
UglifyResult result = Uglify.Js(jsWithErrors, "test.js", settings);
// Check if minification produced any errors
if (result.HasErrors)
{
Console.WriteLine("Minification failed with errors:");
foreach (var error in result.Errors.Where(e => e.IsError))
{
Console.WriteLine($" Error: {error.Message}");
Console.WriteLine($" File: {error.File}, Line: {error.StartLine}, Column: {error.StartColumn}");
}
}
else
{
Console.WriteLine("Minified code:");
Console.WriteLine(result.Code);
}
// Process warnings (non-fatal issues)
var warnings = result.Errors.Where(e => !e.IsError);
foreach (var warning in warnings)
{
Console.WriteLine($"Warning: {warning.Message} at line {warning.StartLine}");
}
// The Code property returns the minified string
string minifiedCode = result.Code;
// UglifyResult can also be implicitly converted to string
string code = result.ToString();
```
--------------------------------
### Minify JavaScript, CSS, and HTML using Uglify class
Source: https://github.com/trullock/nuglify/blob/master/readme.md
Demonstrates the basic usage of the Uglify class to minify JavaScript, CSS, and HTML strings. The Uglify class serves as the primary entry point for these operations.
```csharp
var jsResult = Uglify.Js("var x = 5; var y = 6;");
Console.WriteLine(jsResult.Code);
var cssResult = Uglify.Css("div { color: #FFF; }");
Console.WriteLine(cssResult.Code);
var htmlResult = Uglify.Html("
This is a text
");
Console.WriteLine(htmlResult.Code);
```
--------------------------------
### CSS Resource Replacement Syntax
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Shows how to use special comments in CSS to trigger resource replacement from a RESX file. The minifier replaces the subsequent property value with the localized string.
```css
body
{
/*[BodyFontFamily]*/
font-family: Arial;
/*[BodyColor]*/
color: black;
}
```
--------------------------------
### CssSettings - CSS Minification Settings
Source: https://context7.com/trullock/nuglify/llms.txt
Provides a settings object for controlling CSS minification, including color optimization, comment preservation, and vendor prefix management.
```APIDOC
## CssSettings - CSS Minification Settings
### Description
Settings object for controlling CSS minification behavior including color handling, comment preservation, and vendor prefix management.
### Method
N/A (This is a settings configuration)
### Endpoint
N/A
### Parameters
#### Request Body (Implicitly used by Uglify.Css)
- **settings** (CssSettings) - Required - An instance of CssSettings to configure minification.
- **ColorNames** (CssColor enum) - Optional - Strategy for color name handling (e.g., Strict).
- **AbbreviateHexColor** (bool) - Optional - Whether to abbreviate hex color codes (e.g., #ffffff to #fff).
- **CommentMode** (CssComment enum) - Optional - How to handle comments (e.g., Important for `/*! ... */`).
- **MinifyExpressions** (bool) - Optional - Whether to minify expressions like `calc()`.
- **RemoveEmptyBlocks** (bool) - Optional - Remove CSS rules with no declarations.
- **DecodeEscapes** (bool) - Optional - Decode unicode escapes.
- **FixIE8Fonts** (bool) - Optional - Fixes for IE8 .EOT font URLs.
- **OutputMode** (OutputMode enum) - Optional - Output format (e.g., SingleLine).
- **TermSemicolons** (bool) - Optional - Whether to add trailing semicolons.
- **ExcludeVendorPrefixes** (string[]) - Optional - Array of vendor prefixes to exclude (e.g., `{"ms", "webkit"}`).
### Request Example
```csharp
using NUglify;
using NUglify.Css;
var settings = new CssSettings
{
// Color optimization
ColorNames = CssColor.Strict,
AbbreviateHexColor = true,
// Comment handling
CommentMode = CssComment.Important,
// Code optimization
MinifyExpressions = true,
RemoveEmptyBlocks = true,
DecodeEscapes = true,
// Browser compatibility
FixIE8Fonts = true,
// Output formatting
OutputMode = OutputMode.SingleLine,
TermSemicolons = false,
// Vendor prefix filtering (remove specific prefixes)
// ExcludeVendorPrefixes = { "ms", "webkit" }
};
var css = @"\n /*! Theme styles */\n .button {\n background-color: #FF0000;\n -webkit-border-radius: 5px;\n -moz-border-radius: 5px;\n border-radius: 5px;\n }\n\n .empty-rule { }\n";
var result = Uglify.Css(css, "theme.css", settings);
Console.WriteLine(result.Code);
```
### Response
#### Success Response (200)
N/A (This is a settings configuration, not an endpoint)
#### Response Example
```css
/*! Theme styles */.button{background-color:red;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}
```
```
--------------------------------
### Optimize Object and Array Initialization
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Replaces verbose constructor calls with literal syntax to reduce code size during minification.
```javascript
var o = {};
var a = [];
var a = [one, two, three];
```
--------------------------------
### NUglify: Default JavaScript Minification - Whitespace and Comments
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Illustrates the default minification process in NUglify, focusing on the removal of unnecessary whitespace and comments. It highlights that only 'important' comments (e.g., /"! ... "/") are preserved.
```javascript
if ( a == 0 )
{
a = 10;
alert(b/a);
}
```
```javascript
if(a==0){a=10;alert(b/a)}
```
--------------------------------
### Extract Text from HTML with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Shows how to extract plain text from HTML content. Includes options for keeping structural elements or preserving specific formatting tags.
```csharp
using NUglify;
using NUglify.Html;
var textResult = Uglify.HtmlToText(@"
Welcome to Our Site
This is important content.
");
Console.WriteLine(textResult.Code);
var structuredResult = Uglify.HtmlToText(htmlContent, HtmlToTextOptions.KeepStructure);
var formattedResult = Uglify.HtmlToText(htmlContent, HtmlToTextOptions.KeepFormatting);
```
--------------------------------
### Minify CSS Source Code with CssParser
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This C# snippet shows how to minify CSS source code using the CssParser class. It demonstrates setting up the parser, attaching an error handler, and parsing the CSS source to obtain the minified output.
```csharp
var parser = new CssParser();
parser.CssError += new EventHandler(OnCssError);
parser.FileContext = sourceFileName;
var crunchedStyles = parser.Parse(source);
```
--------------------------------
### Pretty Print CSS with NUglify
Source: https://context7.com/trullock/nuglify/llms.txt
Configures NUglify's CSS minifier for readable, formatted output. This setting preserves all comments and ensures the output is presented on multiple lines, making it suitable for debugging or development environments.
```csharp
using NUglify;
using NUglify.Css;
var prettyCssSettings = CssSettings.Pretty();
// Settings: CommentMode = All, MinifyExpressions = false, OutputMode = MultipleLines
var minifiedCss = ".btn{color:red;padding:10px}.container{margin:0 auto;max-width:1200px}";
var prettyCss = Uglify.Css(minifiedCss, "styles.css", prettyCssSettings);
Console.WriteLine(prettyCss.Code);
```
--------------------------------
### Manual Variable Renaming with NUglify in C#
Source: https://context7.com/trullock/nuglify/llms.txt
Demonstrates how to configure NUglify's CodeSettings in C# to manually rename specific JavaScript identifiers (properties and variables) during the minification process. It shows adding rename pairs individually and via a string, checking if pairs exist, and clearing them.
```csharp
using NUglify;
using NUglify.JavaScript;
var settings = new CodeSettings
{
MinifyCode = true,
ManualRenamesProperties = true
};
// Add rename pairs: originalName -> newName
settings.AddRenamePair("longFunctionName", "fn");
settings.AddRenamePair("verboseVariableName", "v");
// Or set via comma-separated string
settings.RenamePairs = "helperFunction=h,utilityMethod=u";
var js = @"
function longFunctionName(verboseVariableName) {
return verboseVariableName * 2;
}
var result = longFunctionName(10);
";
var result = Uglify.Js(js, settings);
Console.WriteLine(result.Code);
// Uses the specified rename mappings
// Check if any rename pairs are set
if (settings.HasRenamePairs)
{
string newName = settings.GetNewName("longFunctionName");
Console.WriteLine($"longFunctionName renamed to: {newName}");
}
// Clear all rename pairs
settings.ClearRenamePairs();
```
--------------------------------
### Apply Global Styles with CSS
Source: https://github.com/trullock/nuglify/blob/master/src/NUglify.Tests/TestData/HTML/tidy-html5-tests/html5/html4/basefont4.html
Demonstrates the modern approach to global text styling by applying CSS properties to the body element, replacing the deprecated basefont tag.
```css
.bf { color: #0000FF; font-size: 80%; font-family: verdana, sans-serif; }
```
--------------------------------
### Defining Nested JavaScript Namespaces
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Shows how to define nested namespaces in JavaScript, ensuring that the parent namespace exists before creating a child namespace. This pattern is useful for organizing larger codebases.
```javascript
if (!window.Msn) {Msn = {};}
Msn.MyNamespace = new function()
{
// namespace object goes here
};
```
--------------------------------
### JavaScript Namespace Registration Helper Function
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Illustrates a helper function 'registerNamespace' for creating nested namespaces, simplifying the process of defining global namespaces. This is particularly useful when not using a framework like Atlas.
```javascript
function registerNamespace(namespace) {
var parts = namespace.split('.');
var current = window;
for (var i = 0; i < parts.length; i++) {
if (!current[parts[i]]) {
current[parts[i]] = {};
}
current = current[parts[i]];
}
}
registerNamespace("Msn.Portals");
Msn.Portals.MyScope = new function()
{
// namespace object goes here
};
```
--------------------------------
### Reduce If-Statement to Logical AND Shortcut
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Shows the reduction of a simple if-statement containing a method call into a more concise logical AND expression. This optimization is only applied to method calls to ensure byte savings.
```javascript
if (obj.method) {
obj.method();
}
// Becomes:
obj.method&&obj.method()
```
--------------------------------
### CodeSettings - JavaScript Minification Settings
Source: https://context7.com/trullock/nuglify/llms.txt
Provides comprehensive settings for controlling JavaScript minification, including variable renaming, code removal, and output formatting.
```APIDOC
## CodeSettings - JavaScript Minification Settings
### Description
Comprehensive settings object for controlling JavaScript minification behavior including variable renaming, code removal, and output formatting.
### Method
N/A (This is a settings configuration)
### Endpoint
N/A
### Parameters
#### Request Body (Implicitly used by Uglify.Js)
- **settings** (CodeSettings) - Required - An instance of CodeSettings to configure minification.
- **MinifyCode** (bool) - Optional - Enable all minification.
- **LocalRenaming** (LocalRenaming enum) - Optional - Strategy for renaming local variables (e.g., CrunchAll).
- **RemoveUnneededCode** (bool) - Optional - Remove unreachable code.
- **RemoveFunctionExpressionNames** (bool) - Optional - Remove unused function expression names.
- **CollapseToLiteral** (bool) - Optional - Convert `new Object()` to `{}`.
- **EvalLiteralExpressions** (bool) - Optional - Evaluate constant expressions.
- **StripDebugStatements** (bool) - Optional - Remove `debugger;` statements.
- **EvalTreatment** (EvalTreatment enum) - Optional - How to handle `eval()` calls (e.g., Ignore).
- **MacSafariQuirks** (bool) - Optional - Add compatibility for Mac Safari.
- **InlineSafeStrings** (bool) - Optional - Break up `` tags within strings.
- **OutputMode** (OutputMode enum) - Optional - Output format (e.g., SingleLine).
- **PreserveImportantComments** (bool) - Optional - Keep comments marked with `/*! ... */`.
- **TermSemicolons** (bool) - Optional - Whether to add trailing semicolons.
- **KnownGlobalNamesList** (string) - Optional - Comma-separated list of global identifiers to prevent renaming.
- **NoAutoRenameList** (string) - Optional - Comma-separated list of identifiers to prevent renaming.
### Request Example
```csharp
using NUglify;
using NUglify.JavaScript;
var settings = new CodeSettings
{
// Minification controls
MinifyCode = true,
LocalRenaming = LocalRenaming.CrunchAll,
RemoveUnneededCode = true,
RemoveFunctionExpressionNames = true,
CollapseToLiteral = true,
EvalLiteralExpressions = true,
// Debug handling
StripDebugStatements = true,
// Safety settings
EvalTreatment = EvalTreatment.Ignore,
MacSafariQuirks = true,
InlineSafeStrings = true,
// Output settings
OutputMode = OutputMode.SingleLine,
PreserveImportantComments = true,
TermSemicolons = false,
// Known globals (suppress undefined warnings)
KnownGlobalNamesList = "jQuery,$,React",
// Prevent renaming specific identifiers
NoAutoRenameList = "$super,exports"
};
var jsCode = @"\n /*! License: MIT */\n function processData(inputData) {\n var result = new Object();\n result.value = inputData * 2;\n debugger;\n return result;\n }\n";
var result = Uglify.Js(jsCode, settings);
Console.WriteLine(result.Code);
```
### Response
#### Success Response (200)
N/A (This is a settings configuration, not an endpoint)
#### Response Example
```javascript
/*! License: MIT */function processData(n){var t={};return t.value=n*2,t}
```
```
--------------------------------
### Uglify.Css
Source: https://github.com/trullock/nuglify/blob/master/readme.md
Minifies CSS code.
```APIDOC
## POST /Uglify/Css
### Description
Minifies the provided CSS source code.
### Method
POST
### Endpoint
Uglify.Css(string code)
### Parameters
#### Request Body
- **code** (string) - Required - The CSS source code to minify.
### Request Example
{
"code": "div { color: #FFF; }"
}
### Response
#### Success Response (200)
- **Code** (string) - The minified CSS code.
#### Response Example
{
"Code": "div{color:#fff}"
}
```
--------------------------------
### Code Analysis with Global Scope Specification
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This command enables code analysis using the -ANALYZE option and specifies known global entities like 'Msn' and 'jQuery' using the -GLOBAL option. This helps in identifying potential bugs by providing a more accurate analysis context.
```bash
ajaxmin –analyze –global:Msn,jQuery inputfile.js –out outputfile.js
```
--------------------------------
### JavaScript Namespace Object with Methods
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates a basic JavaScript namespace object pattern where public methods and properties are defined. NUglify will rename internal variables and functions while preserving public interface.
```javascript
var my = {};
my.Status = 0;
my.Start = function(url)
{
if (my.Status == 0)
{
startRequest(url);
}
else
{
alert("request processing");
}
}
my.Stop = function()
{
if (my.Status != 0)
{
cancelRequest();
}
}
function startRequest(url)
{
// kick off the request
my.Status = 1;
}
function cancelRequest()
{
// cancel a pending request
my.Status = 0;
};
```
--------------------------------
### NUglify: Handling Debug Statements with -DEBUG Option
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates how NUglify's -DEBUG option handles debugger statements and debug-related library calls. By default, these are removed. The option can be set to 'true' to preserve them. Debug-only code blocks can be marked using special comments.
```javascript
debugger;
Web.Debug.Output("foo");
$Debug.Track("bar");
Debug.fail("debug fail");
WAssert(condition,message);
var wnd = new $Debug.DebugWindow();
```
```javascript
var wnd={};
```
```javascript
///#DEBUG
Code between these two comments will be removed in normal mode,
and only shown when in debug mode
///#ENDDEBUG
```
```bash
ajaxmin –debug:true inputfile.js –out outputfile.js
```
--------------------------------
### Debug Mode Resource Injection
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates the output when using the -ECHO option, which preserves the original code and injects the full resource object for debugging purposes.
```javascript
var Strings={Greeting:"Hello!",Praise:"Excellent!"};
document.write("
" + Strings.Greeting + "
");
alert(Strings.Praise);
```
--------------------------------
### Uglify.Html
Source: https://github.com/trullock/nuglify/blob/master/readme.md
Minifies HTML content.
```APIDOC
## POST /Uglify/Html
### Description
Minifies the provided HTML content.
### Method
POST
### Endpoint
Uglify.Html(string html, HtmlSettings settings)
### Parameters
#### Request Body
- **html** (string) - Required - The HTML content to minify.
- **settings** (object) - Optional - Configuration settings for HTML minification.
### Request Example
{
"html": "
This is a text
"
}
### Response
#### Success Response (200)
- **Code** (string) - The minified HTML code.
#### Response Example
{
"Code": "
This is a text
"
}
```
--------------------------------
### NUglify CSS Minification Options
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
NUglify provides command-line options to customize CSS minification. These include controlling comment preservation, color name usage (HEX, STRICT, MAJOR), and semicolon termination.
```bash
--CSS
--COLORS:HEX | STRICT | MAJOR
--COMMENTS:NONE | ALL | HACKS
--TERM
--ANALYZE
--ECHO
```
--------------------------------
### CodeSettings Properties
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Details the properties available in the CodeSettings object for customizing JavaScript minification.
```APIDOC
## CodeSettings Properties
### Description
These properties allow fine-grained control over the JavaScript minification process when using the DLL API.
### Properties
- **CollapseToLiteral** (bool) - Optional - Converts `new Object()` to `{}` and `new Array()` to `[]`. Defaults to `false`.
- **CombineDuplicateLiterals** (bool) - Optional - Combines duplicate literals (numbers, strings, nulls) into local variables to reduce code size. Defaults to `false`.
- **EvalTreatment** (EvalTreatment) - Optional - Controls how `eval` statements are handled to balance minification and safety. Options: `MakeAllSafe`, `Ignore`, `MakeImmediateSafe`. Defaults to `MakeAllSafe`.
- **IndentSize** (int) - Optional - Specifies the number of spaces to use for indentation when `OutputMode` is set to `MultipleLines`. Defaults to `4`.
- **LocalRenaming** (LocalRenaming) - Optional - Determines the level of local variable and function renaming. Options: `KeepAll` (default), `CrunchAll`, `KeepLocalizationVars`.
```
--------------------------------
### Uglify.Js
Source: https://github.com/trullock/nuglify/blob/master/readme.md
Minifies JavaScript code.
```APIDOC
## POST /Uglify/Js
### Description
Minifies the provided JavaScript source code.
### Method
POST
### Endpoint
Uglify.Js(string code)
### Parameters
#### Request Body
- **code** (string) - Required - The JavaScript source code to minify.
### Request Example
{
"code": "var x = 5; var y = 6;"
}
### Response
#### Success Response (200)
- **Code** (string) - The minified JavaScript code.
#### Response Example
{
"Code": "var x=5,y=6"
}
```
--------------------------------
### JavaScript Conditional-Compilation Comments with NUglify
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates how NUglify processes conditional-compilation comments in JavaScript. It retains comments that are at statement boundaries or contain only variable references within expressions, while ignoring others.
```javascript
var ie=false;/*@cc_on ie=true;@*/alert(ie?"Internet Explorer":"NOT Internet Explorer")
```
```javascript
var ie/*@cc_on = 1 @*/;
alert(ie ? "Internet Explorer" : "NOT Internet Explorer");
```
```javascript
var ie/*@cc_on=1@*/;
alert(ie?"Internet Explorer":"NOT Internet Explorer")
```
```javascript
//@set @fourteen = 14
var fourteen = /*@fourteen @*/;
alert(/*@_jscript_version @*/);
```
```javascript
/*@set@fourteen=14@*/var fourteen=/*@fourteen@*/;alert(/*@_jscript_version@*/)
```
```javascript
var isMSIE = /*@cc_on!@*/0;
```
```javascript
var isMSIE=0
```
--------------------------------
### Combine Variable Declarations into For-Loop Initializer
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
Demonstrates how NUglify combines preceding var statements into a for-loop initializer when the variable is directly assigned. It also highlights limitations when using the comma operator.
```javascript
var n = 10, i;
for (i = 5; i > 0; --i) {
n *= i;
}
// Becomes:
for(var n=10,i=5;i>0;--i)n*=i
```
--------------------------------
### Parse JavaScript Source Code with JSParser
Source: https://github.com/trullock/nuglify/blob/master/doc/readme.md
This C# snippet demonstrates how to use the JSParser class to parse JavaScript source code. It includes error handling for compilation errors and exceptions, and converts the parsed abstract syntax tree back into minified code.
```csharp
JSParser parser = new JSParser(source, null);
string minified;
parser.CompilerError += new CompilerErrorHandler(OnCompilerError);
try
{
Block scriptBlock = parser.Parse(settings);
if (scriptBlock != null)
{
minified = scriptBlock.ToCode();
}
}
catch (JScriptException e)
{
// other error handling
}
```