3
votes

Many tutorials have the goog/base.js file included in a script tag and then use goog.require('your_script') to start the app running. For example, here is the header of an HTML file from the linked tutorial:

<script type="text/javascript" src="out/goog/base.js"></script>
<script type="text/javascript" src="hello.js"></script>
<script type="text/javascript">goog.require('hello');</script>

I understand that Google Closure Library is used to compile Clojurescript into Javascript. Why is it being required in the HTML page as well? Can't it compile itself (or its necessary components using advanced compilation) into the hello.js in the example above?

What I really want is to only require a single javascript file and not the dozens of files in /goog/. Isn't that what a compiler is for? I just don't understand why it needs to be included in the page.

1

1 Answers

9
votes

You only need to include the goog/base.js header when you are compiling with :optimizations :none.

The reason that :optimizations :none produces multiple files is that the Google Closure compiler is not run at all with this setting. Instead the ClojureScript compiler simply writes the compiled JavaScript directly to file rather than passing it through the Closure compiler. Therefore the JavaScript produced is neither optimized nor multiple files concatenated into a single JavaScript file. There is also a discussion regarding this compilation mode available on page 21 of ClojureScript: Up and Running (free sample including page 21 is available here)

I personally rarely use :optimizations :none and rather use :simple during development and :advanced for production.

Both :simple and :advanced produce only a single JavaScript file as output which then only requires a single script tag, e.g.

  <script src="/js/myapp.js" type="text/javascript"></script>

I have provided a sample cljsbuild configuration below:

 :cljsbuild {:builds [{:id "dev"
                       :source-paths ["src"]
                       :compiler {:output-to "resources/static/js-dev/myapp.js"
                                  :output-dir "resources/static/js-dev"
                                  :optimizations :simple
                                  :preamble ["react/react.min.js"]
                                  :externs ["react/externs/react.js"]
                                  :source-map "resources/static/js-dev/myapp.js.map"
                                  :pretty-print true}}

                      {:id "live"
                       :source-paths ["src"]
                       :compiler {:output-to "resources/static/js-live/myapp.js"
                                  :output-dir "resources/static/js-live"
                                  :optimizations :advanced
                                  :pretty-print false
                                  :preamble ["react/react.min.js"]
                                  :externs ["react/externs/react.js"]}}]}