杰瑞科技汇

yuicompressor python如何使用?

Of course! Using YUI Compressor from Python is a common task for web developers who want to minify their JavaScript and CSS files as part of a build or deployment process.

yuicompressor python如何使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the different ways to do it, from the simplest method to the most robust and recommended one.

What is YUI Compressor?

YUI Compressor is a JavaScript and CSS minifier created by the Yahoo! User Interface team. It reduces the size of your code by:

  • Removing comments and whitespace.
  • Shortening local variable names (e.g., var myVariable becomes var a).
  • Optimizing CSS selectors and properties.

⚠️ Important Note: The original YUI Compressor project is no longer actively maintained. The last release was in 2025. While it still works, many developers have moved to more modern, actively maintained alternatives like Terser (for JS) and CSSNano or Clean-CSS (for CSS). However, if you need to use YUI Compressor specifically, here's how.


Method 1: Using the yui-compressor Python Package (Easiest)

This is the most straightforward method. It's a Python wrapper that bundles the Java-based YUI Compressor JAR file, so you don't have to manage Java yourself.

yuicompressor python如何使用?-图2
(图片来源网络,侵删)

Installation

First, install the package using pip:

pip install yui-compressor

Basic Usage in Python

You can import the compress function and use it directly in your Python scripts.

from yui_compressor import compress
# --- Minify CSS ---
css_code = """
/* This is a comment */
body {
    font-family: Arial, sans-serif;
    color: #333333;
    margin: 0;
    padding: 20px;
}
h1 {
    font-size: 24px;
    color: blue;
}
"""
minified_css = compress(css_code, type='css')
print("--- Minified CSS ---")
print(minified_css)
print("\n" + "="*30 + "\n")
# --- Minify JavaScript ---
js_code = """
function sayHello(name) {
    // Greets a person
    var greeting = "Hello, " + name + "!";
    console.log(greeting);
    return greeting;
}
sayHello("World");
"""
minified_js = compress(js_code, type='js')
print("--- Minified JS ---")
print(minified_js)

Command-Line Interface (CLI)

The package also provides a handy command-line tool, which is great for build scripts.

# Minify a single CSS file
yui-compressor input.css -o output.min.css
# Minify a single JS file
yui-compressor input.js -o output.min.js
# Minify a JS file and show the compression ratio
yui-compressor input.js -v

Advanced Usage: Processing a Whole Directory

A very common use case is to minify all .js and .css files in a project. Here's a Python script to do that.

yuicompressor python如何使用?-图3
(图片来源网络,侵删)
import os
import shutil
from yui_compressor import compress
def minify_directory(input_dir, output_dir):
    """
    Minifies all .js and .css files from input_dir and saves them to output_dir.
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print(f"Created output directory: {output_dir}")
    for filename in os.listdir(input_dir):
        input_path = os.path.join(input_dir, filename)
        if filename.endswith('.js'):
            output_path = os.path.join(output_dir, filename.replace('.js', '.min.js'))
            file_type = 'js'
        elif filename.endswith('.css'):
            output_path = os.path.join(output_dir, filename.replace('.css', '.min.css'))
            file_type = 'css'
        else:
            continue # Skip other files
        print(f"Minifying {filename}...")
        with open(input_path, 'r', encoding='utf-8') as f_in:
            content = f_in.read()
        minified_content = compress(content, type=file_type)
        with open(output_path, 'w', encoding='utf-8') as f_out:
            f_out.write(minified_content)
        print(f"  -> Saved to {os.path.basename(output_path)}")
# --- Example Usage ---
source_directory = 'assets'
destination_directory = 'assets-min'
# Clean destination directory if it exists
if os.path.exists(destination_directory):
    shutil.rmtree(destination_directory)
minify_directory(source_directory, destination_directory)
print("\nMinification complete!")

Method 2: Using the Official Java JAR (More Control)

This method requires you to have Java installed on your system. You download the official YUI Compressor JAR file and call it as a subprocess from Python. This gives you more control over the Java version or if you already have the JAR file.

Prerequisites

  • Java Development Kit (JDK): You need Java installed. Check by running java -version in your terminal.
  • YUI Compressor JAR: Download the yuicompressor-x.y.z.jar file from the official YUI Compressor GitHub releases page.

Python Subprocess Example

This Python script will use the subprocess module to call the JAR file.

import subprocess
import os
def minify_with_jar(input_path, output_path, jar_path="yuicompressor-2.4.8.jar"):
    """
    Minifies a file using the YUI Compressor JAR via a subprocess call.
    """
    if not os.path.exists(jar_path):
        print(f"Error: YUI Compressor JAR not found at '{jar_path}'")
        return
    command = [
        "java",
        "-jar",
        jar_path,
        input_path,
        "-o",
        output_path
    ]
    try:
        print(f"Running command: {' '.join(command)}")
        # Using check_call will raise an error if the command fails
        subprocess.check_call(command)
        print(f"Successfully minified '{input_path}' to '{output_path}'")
    except subprocess.CalledProcessError as e:
        print(f"Error during minification: {e}")
    except FileNotFoundError:
        print("Error: 'java' command not found. Please ensure Java is installed and in your PATH.")
# --- Example Usage ---
input_css_file = "assets/style.css"
output_css_file = "assets-min/style.min.css"
input_js_file = "assets/script.js"
output_js_file = "assets-min/script.min.js"
# Make sure the JAR file is in the same directory or provide the full path
JAR_FILE = "yuicompressor-2.4.8.jar" 
# Create output directory if it doesn't exist
os.makedirs("assets-min", exist_ok=True)
minify_with_jar(input_css_file, output_css_file, JAR_FILE)
minify_with_jar(input_js_file, output_js_file, JAR_FILE)

Method 3: The Modern Alternative (Recommended)

Since YUI Compressor is outdated, for new projects, it's highly recommended to use a modern, pure-Python minifier. The most popular choice is rumps, which uses Terser for JS and CSSTidy for CSS.

Installation

pip install rumps

Usage

The API is very similar to the yui-compressor package.

from rumps import minify
js_code = """
function sayHello(name) {
    var greeting = "Hello, " + name + "!";
    console.log(greeting);
}
"""
minified_js = minify(js_code, type='js')
print("--- Minified JS with rumps ---")
print(minified_js)
css_code = """
body { font-family: Arial; color: #333; }
h1 { font-size: 24px; }
"""
minified_css = minify(css_code, type='css')
print("\n--- Minified CSS with rumps ---")
print(minified_css)

Summary and Recommendation

Method Pros Cons Best For
yui-compressor Python Package Easiest setup. No Java needed. Simple Python API. YUI Compressor is outdated. Quick tasks or projects where you must use YUI Compressor and want to avoid Java dependency management.
Official Java JAR Uses the official tool. More control over Java environment. Requires Java installation. More complex (subprocess calls). Existing build systems already using Java or when you need a specific version of the JAR.
Modern Alternative (rumps) Actively maintained. Pure Python. Faster. Uses superior modern minifiers (Terser, CSSTidy). Not YUI Compressor. Almost all new Python projects. This is the recommended path for future-proof and efficient minification.

Final Recommendation:

  • If you must use YUI Compressor, use Method 1 (yui-compressor package). It's the simplest and most Pythonic way.
  • If
分享:
扫描分享到社交APP
上一篇
下一篇