We've been hosted on Digital Ocean since 2013 and highly recommend it for your hosting too. Try it now!

CSS Minifier

Online CSS Minifier/Compressor. Free! Provides an API. Simple Quick and Fast.

Written and hosted by Andrew Chilton (@andychilton) since 2009.

Swift

Thanks to Mark Malström for this contribution.

import Foundation
import Combine

enum CodeType {
    case javaScript
    case css

    var url: URL {
        switch self {
        case .javaScript: return URL(string: "https://javascript-minifier.com/raw")!
        case .css: return URL(string: "https://cssminifier.com/raw")!
        }
    }
}

func minify(code: String, of type: CodeType) -> AnyPublisher {
    let value = "input=\(code)"

    var request = URLRequest(url: type.url)
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpBody = value.data(using: .utf8)

    return URLSession.shared.dataTaskPublisher(for: request)
        .tryMap { output -> String in
            guard let httpResponse = output.response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                    throw URLError(.badServerResponse)
            }

            guard let string = String(data: output.data, encoding: .utf8) else {
                throw URLError(.badServerResponse)
            }

            return string
        }
        .eraseToAnyPublisher()
}

// Usage JS

var cancellables: Set = []

let js = """
    console.log( 1 );
"""

minify(code: js, of: .javaScript)
    .assertNoFailure()
    .sink { print($0) }
    .store(in: &cancellables)

// Usage CSS

let css = """
    .red {
        color: #ff0000;
    }
"""

minify(code: css, of: .css)
    .assertNoFailure()
    .sink { print($0) }
    .store(in: &cancellables)

Many people have sent language examples over the years, but we want more! We'd love to add more examples in your favourite programming language, so please send them our way. Email andychilton at that gmail place in the sky, tweet me @andychilton, or open an issue or PR on webdev-sh/cssminfier.com.

Click on the language of your choice to see an example: