`
gui1401
  • 浏览: 50150 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

javascript 压缩 JSMin

    博客分类:
  • js
阅读更多

c#

using System;
using System.IO;

/* Originally written in 'C', this code has been converted to the C# language.
 * The author's copyright message is reproduced below.
 * All modifications from the original to C# are placed in the public domain.
 */

/* jsmin.c
   2007-05-22

Copyright (c) 2002 Douglas Crockford  (www.crockford.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

namespace JavaScriptSupport
{
    class JavaScriptMinifier
    {
        const int EOF = -1;

        StreamReader sr;
        StreamWriter sw;
        int theA;
        int theB;
        int theLookahead = EOF;


        static void Main( string[] args )
        {
            if( args.Length != 2 )
            {
                Console.WriteLine( "invalid arguments, 2 required, 1 in, 1 out" );
                return;
            }
            new JavaScriptMinifier().Minify( args[0], args[1] );
        }

        public void Minify( string src, string dst )
        {
            using( sr = new StreamReader( src ) )
            {
                using( sw = new StreamWriter( dst ) )
                {
                    jsmin();
                }
            }
        }

        /* jsmin -- Copy the input to the output, deleting the characters which are
                insignificant to JavaScript. Comments will be removed. Tabs will be
                replaced with spaces. Carriage returns will be replaced with linefeeds.
                Most spaces and linefeeds will be removed.
        */
        void jsmin()
        {
            theA = '\n';
            action( 3 );
            while( theA != EOF )
            {
                switch( theA )
                {
                    case ' ':
                    {
                        if( isAlphanum( theB ) )
                        {
                            action( 1 );
                        }
                        else
                        {
                            action( 2 );
                        }
                        break;
                    }
                    case '\n':
                    {
                        switch( theB )
                        {
                            case '{':
                            case '[':
                            case '(':
                            case '+':
                            case '-':
                            {
                                action( 1 );
                                break;
                            }
                            case ' ':
                            {
                                action( 3 );
                                break;
                            }
                            default:
                            {
                                if( isAlphanum( theB ) )
                                {
                                    action( 1 );
                                }
                                else
                                {
                                    action( 2 );
                                }
                                break;
                            }
                        }
                        break;
                    }
                    default:
                    {
                        switch( theB )
                        {
                            case ' ':
                            {
                                if( isAlphanum( theA ) )
                                {
                                    action( 1 );
                                    break;
                                }
                                action( 3 );
                                break;
                            }
                            case '\n':
                            {
                                switch( theA )
                                {
                                    case '}':
                                    case ']':
                                    case ')':
                                    case '+':
                                    case '-':
                                    case '"':
                                    case '\'':
                                    {
                                        action( 1 );
                                        break;
                                    }
                                    default:
                                    {
                                        if( isAlphanum( theA ) )
                                        {
                                            action( 1 );
                                        }
                                        else
                                        {
                                            action( 3 );
                                        }
                                        break;
                                    }
                                }
                                break;
                            }
                            default:
                            {
                                action( 1 );
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        /* action -- do something! What you do is determined by the argument:
                1   Output A. Copy B to A. Get the next B.
                2   Copy B to A. Get the next B. (Delete A).
                3   Get the next B. (Delete B).
           action treats a string as a single character. Wow!
           action recognizes a regular expression if it is preceded by ( or , or =.
        */
        void action( int d )
        {
            if( d <= 1 )
            {
                put( theA );
            }
            if( d <= 2 )
            {
                theA = theB;
                if( theA == '\'' || theA == '"' )
                {
                    for( ; ; )
                    {
                        put( theA );
                        theA = get();
                        if( theA == theB )
                        {
                            break;
                        }
                        if( theA <= '\n' )
                        {
                            throw new Exception( string.Format( "Error: JSMIN unterminated string literal: {0}\n", theA ) );
                        }
                        if( theA == '\\' )
                        {
                            put( theA );
                            theA = get();
                        }
                    }
                }
            }
            if( d <= 3 )
            {
                theB = next();
                if( theB == '/' && (theA == '(' || theA == ',' || theA == '=' ||
                                    theA == '[' || theA == '!' || theA == ':' ||
                                    theA == '&' || theA == '|' || theA == '?' ||
                                    theA == '{' || theA == '}' || theA == ';' ||
                                    theA == '\n') )
                {
                    put( theA );
                    put( theB );
                    for( ; ; )
                    {
                        theA = get();
                        if( theA == '/' )
                        {
                            break;
                        }
                        else if( theA == '\\' )
                        {
                            put( theA );
                            theA = get();
                        }
                        else if( theA <= '\n' )
                        {
                            throw new Exception( string.Format( "Error: JSMIN unterminated Regular Expression literal : {0}.\n", theA ) );
                        }
                        put( theA );
                    }
                    theB = next();
                }
            }
        }
        /* next -- get the next character, excluding comments. peek() is used to see
                if a '/' is followed by a '/' or '*'.
        */
        int next()
        {
            int c = get();
            if( c == '/' )
            {
                switch( peek() )
                {
                    case '/':
                    {
                        for( ; ; )
                        {
                            c = get();
                            if( c <= '\n' )
                            {
                                return c;
                            }
                        }
                    }
                    case '*':
                    {
                        get();
                        for( ; ; )
                        {
                            switch( get() )
                            {
                                case '*':
                                {
                                    if( peek() == '/' )
                                    {
                                        get();
                                        return ' ';
                                    }
                                    break;
                                }
                                case EOF:
                                {
                                    throw new Exception( "Error: JSMIN Unterminated comment.\n" );
                                }
                            }
                        }
                    }
                    default:
                    {
                        return c;
                    }
                }
            }
            return c;
        }
        /* peek -- get the next character without getting it.
        */
        int peek()
        {
            theLookahead = get();
            return theLookahead;
        }
        /* get -- return the next character from stdin. Watch out for lookahead. If
                the character is a control character, translate it to a space or
                linefeed.
        */
        int get()
        {
            int c = theLookahead;
            theLookahead = EOF;
            if( c == EOF )
            {
                c = sr.Read();
            }
            if( c >= ' ' || c == '\n' || c == EOF )
            {
                return c;
            }
            if( c == '\r' )
            {
                return '\n';
            }
            return ' ';
        }
        void put( int c )
        {
            sw.Write( (char)c );
        }
        /* isAlphanum -- return true if the character is a letter, digit, underscore,
                dollar sign, or non-ASCII character.
        */
        bool isAlphanum( int c )
        {
            return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
                (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' ||
                c > 126);
        }
    }
}

java

/*
 * 
 * JSMin.java 2006-02-13
 * 
 * Updated 2007-08-20 with updates from jsmin.c (2007-05-22)
 * 
 * Copyright (c) 2006 John Reilly (www.inconspicuous.org)
 * 
 * This work is a translation from C to Java of jsmin.c published by
 * Douglas Crockford.  Permission is hereby granted to use the Java 
 * version under the same conditions as the jsmin.c on which it is
 * based.  
 * 
 * 
 * 
 * 
 * jsmin.c 2003-04-21
 * 
 * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * The Software shall be used for Good, not Evil.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.inconspicuous.jsmin;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;


public class JSMin {
	private static final int EOF = -1;

	private PushbackInputStream in;
	private OutputStream out;

	private int theA;
	private int theB;
	
	public JSMin(InputStream in, OutputStream out) {
		this.in = new PushbackInputStream(in);
		this.out = out;
	}

	/**
	 * isAlphanum -- return true if the character is a letter, digit,
	 * underscore, dollar sign, or non-ASCII character.
	 */
	static boolean isAlphanum(int c) {
		return ( (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || 
				 (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' || 
				 c > 126);
	}

	/**
	 * get -- return the next character from stdin. Watch out for lookahead. If
	 * the character is a control character, translate it to a space or
	 * linefeed.
	 */
	int get() throws IOException {
		int c = in.read();

		if (c >= ' ' || c == '\n' || c == EOF) {
			return c;
		}

		if (c == '\r') {
			return '\n';
		}
		
		return ' ';
	}

	
	
	/**
	 * Get the next character without getting it.
	 */
	int peek() throws IOException {
		int lookaheadChar = in.read();
		in.unread(lookaheadChar);
		return lookaheadChar;
	}

	/**
	 * next -- get the next character, excluding comments. peek() is used to see
	 * if a '/' is followed by a '/' or '*'.
	 */
	int next() throws IOException, UnterminatedCommentException {
		int c = get();
		if (c == '/') {
			switch (peek()) {
			case '/':
				for (;;) {
					c = get();
					if (c <= '\n') {
						return c;
					}
				}

			case '*':
				get();
				for (;;) {
					switch (get()) {
					case '*':
						if (peek() == '/') {
							get();
							return ' ';
						}
						break;
					case EOF:
						throw new UnterminatedCommentException();
					}
				}

			default:
				return c;
			}

		}
		return c;
	}

	/**
	 * action -- do something! What you do is determined by the argument: 1
	 * Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B.
	 * (Delete A). 3 Get the next B. (Delete B). action treats a string as a
	 * single character. Wow! action recognizes a regular expression if it is
	 * preceded by ( or , or =.
	 */

	void action(int d) throws IOException, UnterminatedRegExpLiteralException,
			UnterminatedCommentException, UnterminatedStringLiteralException {
		switch (d) {
		case 1:
			out.write(theA);
		case 2:
			theA = theB;

			if (theA == '\'' || theA == '"') {
				for (;;) {
					out.write(theA);
					theA = get();
					if (theA == theB) {
						break;
					}
					if (theA <= '\n') {
						throw new UnterminatedStringLiteralException();
					}
					if (theA == '\\') {
						out.write(theA);
						theA = get();
					}
				}
			}
			
		case 3:
			theB = next();
			if (theB == '/' && (theA == '(' || theA == ',' || theA == '=' ||
                    			theA == ':' || theA == '[' || theA == '!' || 
                    			theA == '&' || theA == '|' || theA == '?' || 
                    			theA == '{' || theA == '}' || theA == ';' || 
                    			theA == '\n')) {
				out.write(theA);
				out.write(theB);
				for (;;) {
					theA = get();
					if (theA == '/') {
						break;
					} else if (theA == '\\') {
						out.write(theA);
						theA = get();
					} else if (theA <= '\n') {
						throw new UnterminatedRegExpLiteralException();
					}
					out.write(theA);
				}
				theB = next();
			}
		}
	}

	/**
	 * jsmin -- Copy the input to the output, deleting the characters which are
	 * insignificant to JavaScript. Comments will be removed. Tabs will be
	 * replaced with spaces. Carriage returns will be replaced with linefeeds.
	 * Most spaces and linefeeds will be removed.
	 */
	public void jsmin() throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException, UnterminatedStringLiteralException{
		theA = '\n';
		action(3);
		while (theA != EOF) {
			switch (theA) {
			case ' ':
				if (isAlphanum(theB)) {
					action(1);
				} else {
					action(2);
				}
				break;
			case '\n':
				switch (theB) {
				case '{':
				case '[':
				case '(':
				case '+':
				case '-':
					action(1);
					break;
				case ' ':
					action(3);
					break;
				default:
					if (isAlphanum(theB)) {
						action(1);
					} else {
						action(2);
					}
				}
				break;
			default:
				switch (theB) {
				case ' ':
					if (isAlphanum(theA)) {
						action(1);
						break;
					}
					action(3);
					break;
				case '\n':
					switch (theA) {
					case '}':
					case ']':
					case ')':
					case '+':
					case '-':
					case '"':
					case '\'':
						action(1);
						break;
					default:
						if (isAlphanum(theA)) {
							action(1);
						} else {
							action(3);
						}
					}
					break;
				default:
					action(1);
					break;
				}
			}
		}
		out.flush();
	}

	class UnterminatedCommentException extends Exception {
	}

	class UnterminatedStringLiteralException extends Exception {
	}

	class UnterminatedRegExpLiteralException extends Exception {
	}

	public static void main(String arg[]) {
		try {
			JSMin jsmin = new JSMin(new FileInputStream(arg[0]), System.out);
			jsmin.jsmin();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (UnterminatedRegExpLiteralException e) {
			e.printStackTrace();
		} catch (UnterminatedCommentException e) {
			e.printStackTrace();
		} catch (UnterminatedStringLiteralException e) {
			e.printStackTrace();
		}
	}


}
js 方法见附件
分享到:
评论

相关推荐

    基于jsmin的javascript批量压缩软件

    这个是基于软件版本的,在线版本的是...使用方法:将jsmin.exe拷贝到你想要压缩的目录中,也可以将你要压缩的所有js文件,拷贝到jsmin.exe所在的目录中(可以是子目录),双击运行软件会提示 然后输入y,然后回车就可关闭

    jsmin js 压缩工具 javascript 压缩工具

    为了优化网站性能,开发者通常会使用像"jsmin"这样的JavaScript压缩工具来减小文件大小。 "jsmin"是一个高效的JavaScript压缩工具,其主要目的是通过删除不必要的字符(如空格、注释和换行)以及缩短变量名来减小JS...

    jsmin javascript压缩工具

    JavaScript是Web开发中不可或缺的一部分,而jsmin是一个广泛使用的JavaScript压缩工具,它的主要目标是减少JavaScript文件的大小,从而提高网页加载速度,降低用户等待时间,提升用户体验。jsmin通过删除不必要的...

    Javascript压缩工具,JsMinGUI

    这就引出了JavaScript压缩的必要性。"JsMinGUI"是一款专为此目的设计的工具,它帮助开发者有效地压缩JavaScript代码,减少文件大小,提高网页性能。 JsMinGUI,全称JavaScript Minifier Graphical User Interface,...

    jsmin javascript精简工具

    "jsmin" 是一个广泛使用的JavaScript压缩工具,由Douglas Crockford开发。它通过删除不必要的字符,如注释、空白和换行,以及将多个小字符串合并为一个字符串来实现代码压缩。这种压缩方式能够显著减小JavaScript...

    JSMin js注释清理及压缩工具下载

    JSMin 是一个JavaScript压缩工具,主要用于减少JavaScript代码的大小,从而提高网页加载速度。这个工具由 Douglas Crockford 创建,他也是JSON(JavaScript Object Notation)格式的创始人。JSMin的主要功能是删除...

    JSMin(javaScript文件压缩)

    由Douglas Crockford创建的JSMin是一个筛选程序,用于JavaScript文件中删除注释和不必要的空格。这个程序通常能够使文件大小减半,从而节省下载时间。 压缩包里包含了用C写的源码,及可执行程序 由于看到三条评论说...

    javascript 压缩工具

    本文将详细介绍JSMin和YUI Compressor这两种常用的JavaScript压缩工具,以及它们在优化代码方面的作用。 一、JSMin JSMin是一款轻量级的JavaScript压缩工具,由Douglas Crockford开发。它的主要功能是删除...

    jsmin v1.1.1.php

    **JSMin v1.1.1.php** 是一个基于PHP实现的JavaScript压缩工具,由Crockford的JSMin Java版本改编而来。这个工具的主要目的是为了优化JavaScript代码,减少其在网络传输中的大小,从而提高网页加载速度。在网页开发...

    jsmin 是一个帮助精简Javascript代码的工具,它会帮助你去除多余的空格,换行,注释等等

    需要注意的是,虽然jsmin在大多数情况下能够正确处理JavaScript代码,但它并不能理解高级语言特性或ES6+的新语法,因此对于包含这些特性的现代JavaScript代码,可能需要更先进的压缩工具,如UglifyJS或Terser。...

    [其他类别]jsmin v1.1.1.php_jsmin.zip

    jsmin是一个JavaScript压缩工具,它的主要功能是通过删除JavaScript代码中的注释、多余空格和换行,以及优化某些表达式,从而减少文件大小,提升网页加载速度。 【描述】:描述信息虽然简洁,但我们可以通过“jsmin...

    jsmin-php:Douglas Crockford的JSMin JavaScript压缩程序PHP端口。 不再维护

    在当前的开发环境中,有许多替代的、更先进的JavaScript压缩工具,它们提供了更好的性能和更全面的功能。例如: 1. **UglifyJS**: 是一个广泛使用的JavaScript压缩器,它能解析、压缩和混淆JavaScript代码,同时...

    一个专门用来压缩JAVASCRIPT代码的工具

    JsMinGUI是一个图形用户界面(GUI)版本的JavaScript压缩工具,它基于Doug Crockford的JsMin算法。这个工具的主要目标是减少JavaScript文件的大小,从而提高网页的加载速度和整体性能。JavaScript压缩的过程通常包括...

    js 压缩工具 AjaxMin4Setup (附使用方法)

    关于javascript(js)和css压缩工具的使用,在之前的网 站性能优化工具-javascript压缩工具JSMin, javascript 压缩工具-YUI-compressor, javascript 压缩工具Dojo compressor ,javascript 压缩工具使用说明-...

    JsMinGUI.rar_JsMin.pas_JsMinGUI.e_Web Page delphi_delphi 压缩_delp

    JsMin是一个流行的JavaScript压缩库,它的源码是用Pascal编写的,文件名为"jsmin.pas"。这个库的核心功能是通过算法分析JS代码,识别并移除无用的字符,同时保持代码的执行逻辑不变。"JsMinGUI.e"则可能是JsMin的...

    javascript压缩工具

    下载完成后运行cmd,然后在命令提示符输入:C:\jsmin.exe &lt;C:\before.js&gt;C:\after.js ...使用JSMin压缩js文件,文件必须符合JSLint的编写风格,不然容易出现错误。 JSMin的压缩主要是清除多余空白和备注。

    JSMIN

    用来压缩javascript的工具,有三个压缩级别,级别一,二较安全,级别三压缩率高但有时会导致程序出错,尤其是句未没有加“;”的情况下。

    harmonyos2-jsmin:Javascript压缩器

    JavaScript 压缩器。 用法 from jsmin import jsmin with open ( 'myfile.js' ) as js_file : minified = jsmin ( js_file . read ()) 您也可以将其作为命令行工具运行: python -m jsmin myfile.js 注意: jsmin...

Global site tag (gtag.js) - Google Analytics