This site has been acquired by Toptal.com.
(Attention! API endpoint has changed)

CSS Minifier

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

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://www.toptal.com/developers/cssminifier/raw")!
        case .css: return URL(string: "https://www.toptal.com/developers/cssminifier/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)

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