有時後會需要看別人寫的 Javascript Code,很多情況該程式碼已經被壓縮或最佳化,然後程式碼就被擠成一列而已,然而,那一些展開後可能是數百數千列的程式碼。

為此,就簡單寫隻 PHP 程式碼,把 Javascript Code 稍稍地排版,例如碰到 { 和 } 要縮排等,我記得以前用 Visual C++ 時,可全選程式碼後按 shtif + F8 就可以排版好了,這已經是七年前的印象,不過手邊沒這種環境,目前只愛用 vim 啦,就簡單寫一下 PHP 來處理。在自行更改 input 跟 output 吧。

程式碼(僅適合觀看,不適合轉完又拿來用喔,因為有些像 regular expression 應該因為此排版而出錯):

<?php
        $raw = file_get_contents( 'bundle.js' );

        $level = 0;
        for( $i=0 ; $i<strlen( $raw ) ; ++$i )
        {   
                if( $level > 0 && $raw[$i] == "\n" )
                {   
                        $sp = '';
                        for( $j=0 ; $j<$level; ++$j )
                                $sp .= "\t";

                        $prev_part = substr( $raw , 0 , $i );
                        $next_part = substr( $raw , $i + 1 );
                        $raw = $prev_part . $raw[ $i ] . $sp . $next_part ;

                        $i += $level;
                }   
                else if( $raw[ $i ] == ';' )
                {   
                        $prev_part = substr( $raw , 0 , $i );
                        $next_part = substr( $raw , $i + 1 );
                        $raw = $prev_part . $raw[ $i ] . "\n" . $next_part ;
                }   
                else if( $raw[ $i ] == '{' )
                {   
                        $prev_part = substr( $raw , 0 , $i );
                        $next_part = substr( $raw , $i + 1 );
                        $raw = $prev_part . $raw[ $i ] . "\n" . $next_part ;

                        ++$level;
                }   
                else if( $level > 0 && $raw[ $i ] == '}' )
                {   
                        --$level;
                        $sp = '';
                        for( $j=0 ; $j<$level; ++$j )
                                $sp .= "\t";

                        $prev_part = substr( $raw , 0 , $i );
                        $next_part = substr( $raw , $i + 1 );
                        $raw = $prev_part . "\n" . $sp . $raw[ $i ] . "\n" . $next_part ;

                        $i += $level + 1 ;      // 1 for first newline
                }   
                echo "$level\n";
        }
        file_put_contents( 'bundle.js.new' , $raw );
?>



changyy 發表在 痞客邦 PIXNET 留言(0) 人氣()