Closure Library
The Closure library is a JavaScript library, comparable to other modern products such as jQuery, Angular, Vue.js, Dojo and MooTools. The encoding style and usage of comments in the Closure library are tailor-made for Closure Compiler. Compared to other JavaScript libraries, it is Closure Compiler's main differentiator. A simple compression experiment found that when using Closure Compiler instead of YUI Compressor, the Closure Lib code can be reduced by 85%, which can have a huge impact on the compiler's code compression capacity.
The implementation of the closure library also focuses on readability and performance. Be thrifty when creating objects, but be generous when naming and including objects. It also has a beautiful event system, class and inheritance support, and several UI components, including a rich text editor, for example. The Closure library code is regularly tested in all browsers and, as far as possible, may also be used in non-browser JavaScript environments.
Since the library is primarily a resource for Google engineers and secondly an open source project, it is certain that every line of code in the library is developed to support at least one Google product. First, introduce the style of the library.
Closure templates provide intuitive syntax for creating efficient JavaScript functions (or objects in Java) that can generate HTML. This makes it easy to create larger HTML / XML strings, which can then be used to build the DOM. Unfortunately, most programming languages do not have native support for templates, so creating a separate template solution is common practice for web frameworks (Python developers often use Django's template system, J2EE has JSP ASP MVC etc.). The unique thing about disabling templates is that the same template can be compiled in Java and JavaScript at the same time. Therefore, those servers on which servers are written in Java (or JavaScript!) Can use the same template on both the server and the client.
It can be used with other template systems such as lit-html, an efficient, extensible, and extensible HTML template library for JavaScript. The next generation HTML template in JavaScript. lit-html allows you to write HTML templates with JavaScript, and then efficiently render and re-render those templates and data to create and update the DOM. Create and update the DOM efficiently lit-html is not a framework, nor does it contain a component model. It focuses on one thing, and only one thing: making and updating the DOM effective. It can be used alone for simple tasks, or combined with frameworks or component models (such as web components) for a fully functional UI development platform. For example, we saw this combination on the YouTube website.
For existing JavaScript applications, the Closure compiler is probably
the most direct and useful Closure tool. Although using it to compile
code written in the style of the Closure library will be the most
effective method, replacing the existing jQuery or Dojo dependencies
with the library can be time consuming. In contrast, Closure Compiler
can be used to replace existing JavaScript compressors (such as minifier or JSMin YUI Compressor), which saves a lot of effort. There are even online services to be found.
The Closure compiler is a JavaScript optimized compiler: it takes
JavaScript source code as input and generates source code with
equivalent behavior as output. In other words, when the output code is
used instead of the input code, the observable effect will be the same
(although the execution speed of the output code may be faster than the
original code).
In addition, like JSLint, the compiler can detect a large number of
errors by performing static checks at compile time. This helps to find
errors earlier, which greatly speeds up the development of JavaScript.
Using a compiler to identify problems is not a substitute for unit
testing, but it can.
Closure Testing Framework
Closure
Testing Framework is a unit testing framework that runs in the browser,
very similar to Jasmine.js, QUnit or Mocha.js. Most Closure Library code has corresponding
tests that run in the Framework. Good programming practice is to create
tests for your own code and run them regularly to identify regressions.
Since Closure Testing Framework runs inside the browser, other software
is needed to automate the process of starting the browser, running tests
and recording results. Selenium ( python WebDriver ) may be the best
solution for this purpose.
Closure CSS
Closure
Stylesheets is a system that adds many Google extensions to the
standard CSS language. Using these extensions, you can define and use
variables, functions, conditions, and hybrid tables in the style sheet,
thus making the style sheet more readable and maintainable. The included
tools can compile style sheets to standard CSS, and support
minification, hair loss, directionality (flip from right to left) and
class renaming.
Some words about code
It is important
to understand the design goals and principles that will prompt the
implementation of closed tools. Most of the design of the toolkit is
driven by the functions of the compiler and the style of the library.
The main purpose of Closure Compiler is to reduce the size of JavaScript
code. Since Google provides JavaScript for many pages and prides itself
on speed (Google engineers wear T-shirts with the words "Fast is my
favorite feature"), the JavaScript required to display the page must be
as small as possible. Even if the browser caches JavaScript, when a page
using JavaScript is reloaded, it must be parsed and executed again. The
smaller the JavaScript, the less time it takes. The only thing that can
make your users (or drive them away) is the speed and usability of the
application.
Take for exapmle APM for informational pages, the
difference is very big. APM pages are used 50% more than regular HTML
with javascript. Because they load comfortably on mobile divices.
The way to write JavaScript code should be efficiently compiled by the
compiler. This is the basis for understanding the design of closure
libraries: the verbosity of the code cannot represent the size of the
compiler. If you need to write more code (or comments) to produce
smaller compiled code, this is better than writing less code to produce
larger compiled code.
For
example, it is acceptable to write a comprehensive utility library, as
long as the compiler can delete the unused parts. Complementary methods
should be replaced with a single parameterized method (for example,
setStatus(status) is preferred to statusOn() and statusOff()). This
reduces the number of method declarations and makes it easier to execute
functions. Therefore, to fully understand the Closure library, you must
also understand how Compiler rewrites JavaScript code.
One
might wonder whether to focus on using a compiler to produce JavaScript
with better performance. The short answer is yes, but since
runtime performance is much harder than code size, it took more
engineering time to improve shrinking performance. Fortunately, many
reductions in code size also improve performance, because many
optimizations result from evaluating expressions at compile time rather
than at runtime.
The compiler is designed to immediately compile all code that can be run
in the application process. There are many potential input sources, but
the compiler will receive all of them at the same time. This is in
contrast to other languages, where part of the source code is compiled
into reusable modules. In Closure, the situation is the opposite: the
source code is initially compiled together and then broken down into
modules that can be gradually loaded by the web application. This is
done to ensure that the variable names used in each module are globally
unique.
Memory Matters caused the
Gmail engineers a considerable amount of pain, it did force them to
invest extra effort into managing memory on the client.
Like most modern programming languages, JavaScript
manages its own memory. Fortunately, this cannot rule out the
possibility of memory leaks, because the inability to release references
to objects that are no longer needed can still cause the application to
run out of memory. The closure library uses goog.Disposable to ensure
that the reference is released as soon as possible so that the object
can be garbage collected.
Closure
Compiler is not the first tool to try to identify problems in JavaScript
code by performing static checks. However, there are limits to how much
you can infer from the source code alone. In order to supplement the
information in the code itself, the compiler uses the comments provided
by the developer, which appear in the form of JavaScript comments.By
commenting the code to indicate the function's parameters and return
types, the compiler can determine when to pass incorrect types of
parameters to the function. Similarly, annotate the code to indicate
which data should be private, so that the compiler can recognize when
the data is accessed illegally. By using these annotations in the code,
you can use the compiler to increase confidence in the correctness of
the code. Although the compiler provides many useful conversions for its input,
the code of the Closure library is also expected to run without being
processed by the compiler. This not only ensures that the input language
is pure JavaScript, but also makes debugging easier because
deobfuscated code is always available. However, the library code used with all commonly available objects
(strings, arrays, functions, etc.) in the JavaScript environment does
not rely on APIs that are only available to the browser. This also makes
the Closure library very suitable for use with server-side JavaScript.Built-in object prototypes, such as objects, functions, arrays and
strings, should not be modified. This allows Closure to be used with
other JavaScript libraries such as jQuery. However, in practice, using
Closure with other libraries is usually not efficient. Each library has
its own logic for event management, string processing, etc. This means
that it may contain duplicate logic, which increases the amount of
JavaScript code to be loaded.Each tool in the Closure kit can be used independently. This is mainly
because the decision to use a particular "closed" tool is made by a
single engineering team at Google, so there is no guarantee that the
team using the compiler will also use the library. Now that Closure is
more mature, the main reason for adopting one tool instead of another is
because the dependence on the original code already relies on similar
tools. When deciding how to best incorporate Closure into an existing
project, you may encounter a similar situation.Currently, each tool in the Closure suite must be downloaded and
installed separately. Since these tools are independent of each other,
each tool is maintained as its own project on https://developers.google.com/closure . Most
projects include a "Featured Download" section, in which the tool and
its documentation can be downloaded as some kind of zip file.
Unfortunately, the Closure repository does not provide such bundled
software, so the only way to get the code is to check it out from the
Subversion repository associated with the project. npm install google-closure-library Or you can checkout current version from git or svnhttps://github.com/google/closure-library.git<html>
<head>
<script src="closure-library/closure/goog/base.js"></script>
<script src="hello.js"></script>
</head>
<body onload="sayHi()">
</body>
</html>goog.require('goog.dom');
goog.require('goog.dom.TagName');
function sayHi() {
var newHeader = goog.dom.createDom(goog.dom.TagName.H1, {'style': 'background-color:#EEE'},
'Hello world!');
goog.dom.appendChild(document.body, newHeader);
}
Additional JavaScript files loaded by Closure.
Getting started with Closure Library explains how to start using Closure Library in your project. This section outlines how to use ClosureBuilder and Closure Compiler in a project to reduce the file to a minimal JavaScript file
You may have noticed that the browser made multiple HTTP requests during the page load. For each Closure Library file required by goog.require(), a new script tag is created to load the file. Each Closure Library file is loaded as a separate HTTP request.
This is very effective for development, because you can see uncompiled source code and use existing debugging tools. But this is not conducive to providing services to users. Loading all these files separately is unnecessary and slow. For real-time applications that serve real users, you will need to provide a "compiled" version of the application. Closure Compiler will take your code and required Closure Library files, strip the comments, make some optimizations, and create a larger file as output. In this way, your server can provide only one file instead of multiple individual files.
The closurebuilder.py tool located in closures/bin/build is a tool used to help build compiled JavaScript files. It scans your files and Closure Library files, and can calculate the order of script files in order of relevance. It can output the file name of the script or its contents in dependency order, or pass the file to Closure Compiler to generate a compiled version.
closure-library/closure/bin/build/closurebuilder.py \
--root=closure-library/ \
--root=projectmap/ \
--namespace="myproject.start"
Each --root flag tells ClosureBuilder to scan the .js files in that directory. The goog.provide and goog.require statements will be scanned in each file, which indicates that the file provides a namespace or requires a namespace provided in another file. Scanning all files allows ClosureBuilder to build memory dependency trees for all namespaces. The --namespace flag tells ClosureBuilder to start from the myproject.start namespace in the tree and get all its dependencies. By default, it outputs the results as a file list in order. For each file in the list, each required namespace is provided by another file that appears earlier in the list.
closure-library/closure/bin/build/closurebuilder.py \
--root=closure-library/ \
--root=projectmap/ \
--namespace="myproject.start" \
--output_mode=compiled \
--compiler_jar=compiler.jar \
> myproject/start-compiled.js
ClosureBuilder writes the output of the compiler to standard output. Here, we transfer it to a file named start-compiled.js. Alternatively, you can use --output_file to specify the file to be written
Put start-compiled.js next to myproject.html, then modify the HTML file to use the compiled version:
<!doctype html>
<html>
<head>
<script src="start-compiled.js"></script>
</head>
<body>
<script>
myproject.start();
</script>
</body>
</html>
Using the closure compiler and the compilation_level of ADVANCED_OPTIMIZATIONS together with the compilation level with SIMPLE_OPTIMIZATIONS or WHITESPACE_ONLY can provide better compression. Compiling with ADVANCED_OPTIMIZATIONS can be more aggressive by converting code and renaming symbols to achieve additional compression. However, this more aggressive method means that you must be extra careful when using ADVANCED_OPTIMIZATIONS to ensure that the output code works the same way as the input code.
closure-library/closure/bin/build/closurebuilder.py \
--root=closure-library/ \
--root=myproject/ \
--namespace="myproject.start" \
--output_mode=compiled \
--compiler_jar=compiler.jar \
--compiler_flags="--js=closure-library/closure/goog/deps.js" \
--compiler_flags="--compilation_level=ADVANCED_OPTIMIZATIONS" \
> start-compiled.js
To run your code you need a web server
If you run your code via file system you will see errors related to cross origin support.
You can of course use something like
python -m SimpleHTTPServer
But I would recommend a Firebase project.
Firebase is Google's mobile platform that helps you quickly develop...
Firebase projects are backed by Google Cloud Platform, letting you scale your app and you can use them tools to publish a web application to a modern hosting.
Please see minimal installation on Firebase project website.
That is an example application from official Google get started.
Comments
Post a Comment