Google Closure Compiler в деталях
Этот раздел посвящен Google Closure Compiler.
Чтобы его написать, мне пришлось буквально разобрать компилятор по косточкам, благо все сырцы в наличии есть. И, как оказалось, оно того стоило.
Инструмент мощный, сложный (поначалу), парой слов тут не отделаешься. Надеюсь, что после прочтения данного раздела он станет для вас простым.
- Введение
Google Closure Compiler - уникальный инструмент, разработанный Google для сжатия и обфускации собственного javascript.
У него есть ряд интересных особенностей, которые отличают его от прочих упаковщиков. читать дальше »
- Оптимизации стандартного режима
Оптимизации Google Closure Compiler делятся на два типа.
Первый тип - стандартные. Они задуманы как безопасные. Эти оптимизации делают внутренние преобразования функций и кода, которые не должны влиять на результат выполнения.
Их знание помогает писать код так, чтобы компилятор оптимизировал его как можно более эффективно. читать дальше »
- Продвинутые оптимизации
Продвинутые оптимизации google closure compiler включаются опцией --compilation_level ADVANCED_OPTIMIZATIONS.
Слово "продвинутые" (advanced) здесь, пожалуй, не совсем подходит. Кардинальное отличие этих оптимизаций от обычных (simple) - в том, что они небезопасны.
Чтобы ими пользоваться - надо уметь это делать. читать дальше »
- Объявление и проверка типов в примерах
Google Closure Compiler, как и любой кошерный компилятор, старается проверить правильность кода и предупредить о возможных ошибках.
Первым делом он, разумеется, проверяет структуру кода и сразу же выдает такие ошибки как пропущенная скобка или лишняя запятая.
Но, кроме этого, он умеет проверять типы переменных, используя как свои собственные знания о встроенных javascript-функциях и преобразованиях типов,
так и информацию о типах из JSDoc, указываемую javascript-разработчиком.
Это обеспечивает то, чем так гордятся компилируемые языки - статическую проверку типов, что позволяет избежать лишних ошибок во время выполнения. читать дальше »
- Оптимальное ООП с Google Closure Compiler
В javascript есть несколько основных стилей объявления объектов и свойств.
Они основаны на разной структуре кода, и поэтому - по-разному сжимаются компилятором.
Цель этой статьи - выбрать наилучший стиль ООП с точки зрения минификации кода и понять, почему ООП в таком стиле сжимается лучше всего. читать дальше »
- Сборка модулей
Google Closure Compiler умеет собирать javascript не в виде одного большого файла, а в виде нескольких модулей.
Так что все страницы могут грузить только один модуль, а дополнительная функциональность - загружаться лишь там, где она нужна.
Для такой сборки используется флаг компилятора --module . читать дальше »
- Кодировка: русский текст
При использовании Google Closure Compiler, как впрочем и других аналогичных упаковщиков, основанных на Rhino, возникают некоторые проблемы с русским текстом.
Эта статья содержит рецепты, как их легко преодолеть. читать дальше »
- Использование внутренних опций и собственные флаги
В этой статье мы разберем, как устроен общий цикл работы Google Closure Compiler, научимся добавлять новые флаги и устанавливать при их помощи внутренние, недокументированные опции компилятора. читать дальше »
- Директива @define, удаление веток компилятором
Директива @define позволяет переопределить глобальную переменную (как правило, константу) в процессе компиляции. Компилятор заменит значение javascript-переменной на новое непосредственно в коде javascript.
А так как это константа, то сжатие продвинутым режимом позволяет тут же заинлайнить ее и оптимизировать соответствующие ветки if . читать дальше »
- Исходный код сжатого фрагмента: closure inspector
В этой статье мы рассмотрим, как просмотреть исходный код сжатого фрагмента при помощи Closure Inspector для Firebug, и как адаптировать это расширение под себя. читать дальше »
- Вывод синтаксического дерева кода
Синтаксическое дерево - внутренняя структура, которую интерпретатор javascript создает из исходного кода.
Обычно синтаксическое дерево создается для выполнения, но также может использоваться и для оптимизации, чем, собственно, и занимается google closure compiler. читать дальше »
- Автоудаление отладочных свойств и объектов
Как правило, в нашем коде есть отладочные вызовы.
Например:
console.info("created "+object)
Или даже такие:
my.ajax.debugSend(message)
Google Closure Compiler позволяет удалять такие вызовы из production-кода. Здесь вопрос даже не столько в размере кода и в быстродействии, как в удобстве. Как правило, никому не нужны вызовы console.debug на боевом сервере.
читать дальше » - Создание собственных аннотаций
Java-фреймворк, на котором построен Google Closure Compiler, может быть расширен. Например, можно добавить новые аннотации, которые делают что-то с кодом. читать дальше »
- Эвристическое переименование свойств
Где-то посередине между продвинутым и обычным сжатием находится эвристическое переименование.
При его использовании Google Closure Compiler переименует все свойства объекта и прототипа, кроме тех, которые начинаются с _подчеркивания.
Эти свойства оптимизатор считает публичными (да-да, не приватными а публичными) и не переименует вообще. читать дальше »
|
1. можно ли как-то заставить гугл компилятор(или только переписав изрядно JAVA сорцы) при компиляции запретить некоторые функции javascript на свое усмотрение (или даже методы объектов), например запретить использование eval или document.getElementByID
2. можно ли задать ему шаблон, который нужно использовать в момент минификации. Например, попросить префиксировать все функции/объекты словом "development_"
чтобы поддерживались альтернитивные синтаксисы функций function myFunction -> function development_myFunction и myFunction: function() -> development_myFunction: function()
спасибо
1. Да, можно, причем никаких патчей для этого не нужно. Свой проход компилятора.
Причем, этот проход можно добавить в качестве опции (там есть такая, свои проходы) в MyCompilerRunner, т.к. он независим.
2. Шаблон - нет, операции идут над деревом кода. А вот создать аналогичные функции с development_ - конечно, можно. Похожие действия выполняются в проходе, обрабатывающем exportSymbol.
Никак не могу найти, как отключить перенос строк или указать побольше (в YUICompressor-е для этого есть флаг --line-break). Подскажите, если кто знает.
Написан же флаг, во введении --formatting PRETTY_PRINT
При этом флаге он вообще все переносит, а нужно наоборот, что бы все в одну линию было.
В одну линию - по умолчанию ведь ?
По умолчанию бьётся на строки где-то по 550 символов длиной
Thanks, that was a really cool read!
streaming tv options
This is such a great resource that you are providing and you give it away for free.
buy quality backlinks
Илья, низкий Вам поклон за проделанную работу. Всё очень доступно и интересно написано. Прочел все статьи.
Однако поблагодарить вас за этот труд я считаю нужным!
Искренне благодарен. Спасибо.
в личный список избранных руководств! низкий поклон за проделаную работу
Проделанная работа вызывает изумление и восторг!
Илья, огромное вам человеческое спасибо!
интересная статья ! +
Здравствуйте. Вопрос такой: можно ли как то декомпилировать этот код? То есть хотя бы короткие пременные вернуть в прежний вид, или хотя бы как то теоритически объясните как возможно привести закомпиленный код в читабельный вид.
На следующем примере, за счет инлайнинга констант closure compiler увеличивает размер исходника почти в три раза (вообще, на сколько угодно, зависит от длины строк bigString1 и bigString2):
Он умеет сжимать CSS? И что вообще есть для сжатия CSS? Что лучше сжимает?
Даже с ADVANCED_OPTIMIZATIONS сэкономил всего 7%. Т.е. смысла использовать нету.
Если изначально код нормально написан то там нечего сжимать.
Правда packer сжал почти на 50%. Но там закодирование стоит, без него только на 65%, но все равно на много лучше гугла.
Странно очень.
Без всяких флагов сжал из 352905 байт в 123744. А нормально написанный код как раз имеет не малый размер за счет комментариев кода.
привет всем на сайте https://safesale.in.ua/ пытались сжать файлы и код, но потом выплывали ошибки и нелогичная структура сайта
I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. enable flash in chrome
Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post.
https://arkserverhosting.co.uk
portable hairdryer
crime scene cleanup
mini carpet cleaner
trulylovelykitchen
An fascinating discussion is value comment. I think that it is best to write extra on this matter, it won’t be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers
結婚指輪
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
婚約指輪
This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.
結婚指輪
Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.
ハワイアンジュエリー 結婚指輪
You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!!
結婚指輪 手作り
It’s appropriate time to make some plans for the future and it is time to be happy. I have read this post and if I could I wish to suggest you few interesting things or advice. Perhaps you could write next articles referring to this article. I desire to read even more things about it!
結婚指輪 福岡
Nice post. I was checking constantly this blog and I am impressed! Extremely helpful information specially the last part I care for such info a lot. I was seeking this particular information for a very long time. Thank you and good luck.
pemf devices
Great content material and great layout. Your website deserves all of the positive feedback it’s been getting.
pemf device
I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.
Thanks so much for this information. I have to let you know I concur on several of the points you make here and others may require some further review, but I can see your viewpoint.
Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that. Thanks so lot for your convene.
click here
This was really an interesting topic and I kinda agree with what you have mentioned here!
I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You.
click here
I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You.
click here
Thank you for taking the time to publish this information very useful!
Cryptocurrency Price Widget
I just want to let you know that I just check out your site and I find it very interesting and informative..
go here
I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information.
Estimators online
This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..
seo
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
carpet cleaning
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
homeostasis
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
immigration attorney
Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post.
Akıllı Ev Sistemleri
Very nice article, I enjoyed reading your post, very nice share, I want to twit this to my followers. Thanks!.
land clearing
Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts.
vy & tea
Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..
funny cards
I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
Ipswich window cleaners
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
product videos
This type of message always inspiring and I prefer to read quality content, so happy to find good place to many here in the post, the writing is just great, thanks for the post.
product videos
I really enjoyed reading this post, big fan. Keep up the good work and please tell me when can you publish more articles or where can I read more on the subject?
injury attorney
I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
retro videogames kopen
Thanks so much for this information. I have to let you know I concur on several of the points you make here and others may require some further review, but I can see your viewpoint.
fender-bender lawyer
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
leaky gut diet
I have not any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
leaky gut diet
All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks
locuri de munca
I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
Harley-Davidson Motorclothes
I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
Automatisierung im Handwerk
Thank you for your posts! Very interesting!
Very good and informative exchange .. Thank you!
192.168.1.254
This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future...
fake grass Sheffield
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
tiler Leeds
I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information.
photo booth sale
This is highly information, crisp and clear. I think that everything has been described in systematic manner so that reader could get maximum information and learn many things.
3d printing Manchester
This is the type of information I’ve long been trying to find. Thank you for writing this information.
printers derby
This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..
roofer Lancaster
Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post.
photo booth sale
I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
mechanic Reading
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing
domótica
You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers.
mechanic Reading
I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
pest control West Yorkshire
I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
maison intelligente
I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog site list and will be checking back soon. Please check out my site as well and let me know what you think.
click this site
Your work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us.
visit here
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
follower kaufen PayPal
The information is very special, I will have to follow you, the information you bring is very real, reflecting correctly and objectively, it is very useful for society to grow together. run 3
I appreciate everything you have added to my knowledge base.Admiring the time and effort you put into your blog and detailed information you offer.Thanks.
abonnenten24
This article gives the light in which we can observe the reality. This is very nice one and gives indepth information. Thanks for this nice article.
clima controlo
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
online marketing
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
forex brokers
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
covid isla mujeres
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
online marketing
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic.
online marketing
Very nice article, I enjoyed reading your post, very nice share, I want to twit this to my followers. Thanks!.
house clearance bridgend
Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..
taco catering
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
buy targeted traffic
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
house clearance bridgend
Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks
removal companies hartlepool
I’ve been searching for some decent stuff on the subject and haven't had any luck up until this point, You just got a new biggest fan!..
Turmeric Essential Oil
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
Heimautomation
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
tree surgeon in colchester
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
tulum pyramids
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
schluesseldienst köln
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
خانه هوشمند
I can set up my new idea from this post. It gives in depth information. Thanks for this valuable information for all,..
خانه هوشمند
Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..
cancun
Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post.
rugalmas ügyvéd Debrecen
Fantastic blog! Do you have any tips and hints for aspiring writers? I’m planning to start my own website soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any suggestions? Many thanks!
cenotes en tulum mexico
I have not any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
otomatisasi rumah
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.
otomatisasi rumah
I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
rumah pintar
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
sikerdíjas pályázatírás debrecenieknek
Отправить комментарий
Приветствуются комментарии:Для остальных вопросов и обсуждений есть форум.