### Install Dependencies
Source: https://github.com/maltsev/htmlnano/blob/master/docs/README.md
Installs project dependencies using npm.
```bash
npm install
```
--------------------------------
### Install htmlnano
Source: https://github.com/maltsev/htmlnano/blob/master/README.md
Install htmlnano using npm. This is the first step before using it in your project.
```bash
npm install htmlnano
```
--------------------------------
### Install htmlnano Dependencies
Source: https://context7.com/maltsev/htmlnano/llms.txt
Install necessary peer dependencies for minifyUrls functionality.
```bash
npm install --save-dev relateurl terser srcset
```
--------------------------------
### Start Local Development Server
Source: https://github.com/maltsev/htmlnano/blob/master/docs/README.md
Starts a local development server for live preview. Changes are reflected without server restart.
```bash
npm start
```
--------------------------------
### Install cssnano and postcss
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Install cssnano and postcss as development dependencies to use the minifyCss feature.
```bash
npm install --save-dev cssnano postcss
```
```bash
yarn add --dev cssnano postcss
```
```bash
pnpm install --save-dev cssnano postcss
```
--------------------------------
### Install htmlnano dependencies
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Installs necessary development dependencies including relateurl, terser, and srcset using npm, yarn, or pnpm.
```bash
npm install --save-dev relateurl terser srcset
# if you prefer yarn
# yarn add --dev relateurl terser srcset
# if you prefer pnpm
# pnpm install --save-dev relateurl terser srcset
```
--------------------------------
### Install PurgeCSS or uncss
Source: https://context7.com/maltsev/htmlnano/llms.txt
Install PurgeCSS for removing unused CSS, or uncss as an alternative (not recommended).
```bash
npm install --save-dev purgecss
# or for uncss (not recommended)
npm install --save-dev uncss
```
--------------------------------
### Create a Custom Preset by Extending a Built-in Preset
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/040-presets.md
This example shows how to create a new preset by extending an existing one (e.g., 'safe') and adding or modifying specific configurations like 'mergeStyles' and 'minifyCss'.
```javascript
const htmlnano = require('htmlnano');
const emailPreset = {
...htmlnano.presets.safe,
mergeStyles: true,
minifyCss: {
safe: true
}
};
htmlnano.process(html, { removeComments: false }, emailPreset)
.then((result) => {
// result.html is minified
})
.catch((err) => {
console.error(err);
});
```
--------------------------------
### Install uncss for htmlnano
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Commands to install the uncss dependency for the removeUnusedCss feature.
```bash
npm install --save-dev uncss
# if you prefer yarn
# yarn add --dev uncss
# if you prefer pnpm
# pnpm install --save-dev uncss
```
--------------------------------
### Merge Styles Example
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Shows how multiple style tags are merged based on media and type attributes.
```html
```
```html
```
--------------------------------
### Install PurgeCSS for htmlnano
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Commands to install the PurgeCSS dependency for the removeUnusedCss feature.
```bash
npm install --save-dev purgecss
# if you prefer yarn
# yarn add --dev purgecss
# if you prefer pnpm
# pnpm install --save-dev purgecss
```
--------------------------------
### Install Terser for JavaScript Minification
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Install Terser as a development dependency to enable the minifyJs feature.
```bash
npm install --save-dev terser
```
```bash
yarn add --dev terser
```
```bash
pnpm install --save-dev terser
```
--------------------------------
### SVG Minification Example
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Demonstrates the transformation of standard SVG markup into a minified version.
```html
```
```html
```
--------------------------------
### Example of collapseBooleanAttributes
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Demonstrates how boolean attributes, empty string attributes, missing value defaults, and specific crossorigin values are collapsed.
```html
```
```html
```
--------------------------------
### Example of minifyAttributes
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Illustrates minification of 'meta[http-equiv="refresh"]' attributes by removing 'url=' prefixes and trimming whitespace.
```html
```
```html
```
--------------------------------
### Remove Optional Tags Example
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Demonstrates the removal of optional HTML tags like html, head, and body.
```html
Title
Hi
```
```html
Title
Hi
```
--------------------------------
### CSS Removal Example
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Shows the removal of unused CSS rules within a style block.
```html
```
```html
```
--------------------------------
### Configure htmlnano for Minifying SVG
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Example of configuring htmlnano to minify SVG content using SVGO with custom plugins and options.
```javascript
htmlnano.process(html, {
minifySvg: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
builtinPluginName: {
optionName: 'optionValue'
},
},
},
}
]
}
});
```
--------------------------------
### Extend Default htmlnano Template Minification Rules
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Example of extending the default htmlnano template minification rules by spreading them and adding a new rule.
```javascript
import { modules } from 'htmlnano';
htmlnano.process(html, {
minifyHtmlTemplate: [
...modules.minifyHtmlTemplate.defaultRules,
{ tag: 'script', attrs: { id: 'my-template' } }
]
});
```
--------------------------------
### Remove Attribute Quotes Example
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Shows how attribute quotes are removed when possible.
```html
```
```html
```
--------------------------------
### Example of deduplicateAttributeValues
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Shows how duplicate values in list-like attributes such as 'rel' and 'class' are removed, preserving whitespace where possible.
```html
click
```
```html
click
```
--------------------------------
### Integrate htmlnano as a PostHTML Plugin
Source: https://context7.com/maltsev/htmlnano/llms.txt
Use htmlnano() as a PostHTML plugin to combine it with other PostHTML transformations in a pipeline. This example shows basic usage with custom options for comment removal and whitespace collapsing.
```javascript
const posthtml = require('posthtml');
const htmlnano = require('htmlnano');
const html = `
})
.catch((err) => {
console.error(err);
});
```
--------------------------------
### Configure htmlnano for Minifying HTML Templates
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Example of configuring htmlnano to minify HTML within specific template tags using custom rules.
```javascript
htmlnano.process(html, {
minifyHtmlTemplate: [
{ tag: 'template', attrs: { id: 'my-template' } },
{ tag: 'script', attrs: { type: 'text/x-handlebars-template' } },
]
});
```
--------------------------------
### Define configuration in a JSON file
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/030-config.md
Use a preset and specific options within a configuration file like .htmlnanorc.json.
```json
{
"preset": "max",
"collapseWhitespace": "conservative",
"removeComments": false
}
```
--------------------------------
### Build Static Website
Source: https://github.com/maltsev/htmlnano/blob/master/docs/README.md
Generates static content for deployment. The output is placed in the 'build' directory.
```bash
npm build
```
--------------------------------
### htmlnano CLI Help
Source: https://github.com/maltsev/htmlnano/blob/master/README.md
View the help information for the htmlnano command-line interface tool. This shows available options for direct usage.
```bash
node_modules/.bin/htmlnano --help
```
--------------------------------
### Use htmlnano via CLI
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/020-usage.md
Execute minification directly from the command line or using a configuration file.
```bash
npx htmlnano --help
```
```bash
echo '{"collapseWhitespace": "all", "removeComments": "all"}' > config.json
npx htmlnano test.html -c config.json
```
--------------------------------
### Configure htmlnano via files
Source: https://context7.com/maltsev/htmlnano/llms.txt
Use .htmlnanorc.json, htmlnano.config.js, or package.json to define project-wide minification settings.
```json
// .htmlnanorc.json
{
"preset": "max",
"collapseWhitespace": "aggressive",
"removeComments": "all",
"minifyCss": {
"preset": "default"
},
"minifyJs": {},
"skipInternalWarnings": true
}
```
```javascript
// htmlnano.config.js
module.exports = {
preset: 'safe',
collapseWhitespace: 'conservative',
removeComments: (comment) => !comment.includes('keep'),
custom: (tree) => {
// Custom transformation
return tree;
}
};
```
```json
// package.json
{
"name": "my-project",
"htmlnano": {
"preset": "safe",
"collapseWhitespace": "aggressive"
}
}
```
--------------------------------
### Use htmlnano via Command Line Interface
Source: https://context7.com/maltsev/htmlnano/llms.txt
Execute minification tasks directly from the terminal using the CLI tool.
```bash
# Install htmlnano
npm install htmlnano
# Show help
npx htmlnano --help
# Minify from file to stdout
npx htmlnano input.html
# Minify with output file
npx htmlnano input.html -o output.html
# Use max preset for aggressive minification
npx htmlnano input.html -p max -o minified.html
# Use custom config file
echo '{"collapseWhitespace": "all", "removeComments": "all"}' > config.json
npx htmlnano input.html -c config.json -o output.html
# Pipe from stdin
echo '
Hello
' | npx htmlnano
# Output:
Hello
# Available presets: safe (default), ampSafe, max
npx htmlnano input.html -p ampSafe -o amp-output.html
```
--------------------------------
### JavaScript API: htmlnano.loadConfig()
Source: https://context7.com/maltsev/htmlnano/llms.txt
Loads and merges configuration from cosmiconfig-supported files (e.g., .htmlnanorc.json, htmlnano.config.js, package.json). Returns a tuple of merged options and the resolved preset.
```APIDOC
## JavaScript API: htmlnano.loadConfig()
### Description
Loads and merges configuration from cosmiconfig-supported files (`.htmlnanorc.json`, `htmlnano.config.js`, `package.json`). Returns a tuple of merged options and the resolved preset.
### Method
`loadConfig([customOptions])`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { loadConfig, presets } from 'htmlnano';
// Load config from default locations (.htmlnanorc.json, htmlnano.config.js, etc.)
const [options, preset] = loadConfig();
// Load config with custom options (options override config file)
const [mergedOptions, mergedPreset] = loadConfig({
collapseWhitespace: 'all',
removeComments: 'all'
});
// Load from specific config file path
const [customOptions, customPreset] = loadConfig({
configPath: './custom-config.json'
});
// Skip config file loading entirely
const [directOptions, directPreset] = loadConfig({
skipConfigLoading: true,
collapseWhitespace: 'conservative'
});
console.log('Merged options:', mergedOptions);
console.log('Preset:', preset === presets.safe ? 'safe' : 'other');
```
### Response
#### Success Response (200)
- **options** (object) - Merged configuration options.
- **preset** (object) - The resolved preset.
#### Response Example
```json
{
"options": {
"removeComments": "all",
"collapseWhitespace": "conservative"
},
"preset": "safe"
}
```
```
--------------------------------
### Process HTML with Custom Options and No Preset
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/040-presets.md
Use this when you want to define all minification options manually without using any built-in presets. Pass an empty object as the preset argument.
```javascript
const htmlnano = require('htmlnano');
const options = {
// Your options
};
htmlnano
.process(html, options, {})
.then(function (result) {
// result.html is minified
})
.catch(function (err) {
console.error(err);
});
```
--------------------------------
### Define Custom Minification Modules
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Demonstrates how to pass custom minification functions or arrays of functions to the options object.
```js
const options = {
custom: function (tree, options) {
// Some minification
return tree;
}
};
```
```js
const options = {
custom: [
function (tree, options) {
// Some minification
return tree;
},
function (tree, options) {
// Some other minification
return tree;
}
]
};
```
--------------------------------
### Specify a custom configuration path
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/030-config.md
Pass a specific file path to the process method using the configPath option.
```js
htmlnano.process(html, {
configPath: 'config.json'
})
```
--------------------------------
### Process HTML with a Specific Preset (ES Modules)
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/040-presets.md
This demonstrates minifying HTML using ES module imports and an async function. It requires 'htmlnano' and the specific preset to be imported.
```javascript
import htmlnano from 'htmlnano';
import ampSafe from 'htmlnano/presets/ampSafe';
const result = await htmlnano.process(html, {}, ampSafe);
```
--------------------------------
### Run a Single Test
Source: https://github.com/maltsev/htmlnano/blob/master/AGENTS.md
Executes a specific test file using mocha after ensuring the project is built.
```bash
npm run build && npx mocha --timeout 5000 --require @swc-node/register --recursive --check-leaks --globals addresses "test/modules/minifyCss.ts"
```
--------------------------------
### Remove Redundant Attributes with htmlnano
Source: https://context7.com/maltsev/htmlnano/llms.txt
Removes attributes that match HTML default values. Disabled by default as it may break attribute selectors. Example shows removal of default 'method', 'type', 'type', 'media', 'loading', and 'decoding' attributes.
```javascript
import htmlnano from 'htmlnano';
const html = `
`;
// Enable removal of redundant attributes
const result = await htmlnano.process(html, { removeRedundantAttributes: true });
// Output:
```
--------------------------------
### Integrate with Gulp
Source: https://context7.com/maltsev/htmlnano/llms.txt
Use gulp-posthtml to incorporate htmlnano into Gulp build pipelines.
```bash
npm install --save-dev gulp-posthtml
```
```javascript
const gulp = require('gulp');
const posthtml = require('gulp-posthtml');
const htmlnano = require('htmlnano');
const htmlnanoOptions = {
removeComments: 'all',
collapseWhitespace: 'aggressive',
minifyCss: { preset: 'default' },
minifyJs: {}
};
gulp.task('minify-html', function() {
return gulp
.src('./src/**/*.html')
.pipe(posthtml([
htmlnano(htmlnanoOptions)
]))
.pipe(gulp.dest('./dist'));
});
gulp.task('default', gulp.series('minify-html'));
```
--------------------------------
### Normalize attribute values
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Demonstrates the normalization of attribute casing and application of default values.
```html
```
```html
```
--------------------------------
### Configure minifyUrls with a base URL (String)
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Sets the base URL for relative URL conversion using a string.
```js
htmlnano.process(html, {
minifyUrls: 'https://example.com' // Valid configuration
});
```
--------------------------------
### Process HTML with a Specific Preset (CommonJS)
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/040-presets.md
Use this to minify HTML with a specific preset like 'ampSafe'. Ensure 'htmlnano' and the preset are required.
```javascript
const htmlnano = require('htmlnano');
const ampSafePreset = require('htmlnano').presets.ampSafe;
htmlnano.process(html, { collapseWhitespace: 'conservative' }, ampSafePreset)
.then((result) => {
// result.html is minified
})
.catch((err) => {
console.error(err);
});
```
--------------------------------
### Collapse Whitespace in HTML
Source: https://github.com/maltsev/htmlnano/blob/master/docs/docs/050-modules.md
Demonstrates different whitespace collapsing strategies using the all, aggressive, and conservative modes.
```html