glosure

package module
v0.0.0-...-82abcba Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2015 License: Apache-2.0 Imports: 18 Imported by: 0

README

Glosure: Closure Compiler for Go

Glosure is a simple http.Handler for compiling JavaScript using the Closure Compiler. Glosure can use either the closure compiler application (requires Java Runtime Environment) or the closure REST API (used if java is not in $PATH).

Note that the REST API has limitations and is not be suitable for large-scale JavaScript projects.

Installation:
# go get github.com/soheilhy/glosure
Example:

First create a closure compiler, and then serve HTTP requests:

cc := glosure.NewCompiler("./example/js/")
// Set compiler options.
http.Handle("/", glosure.GlosureServer(cc))
http.ListenAndServe(":8080", nil);

Or even simpler if you do not need to customize the compiler:

http.Handle("/", glosure.GlosureServerWithRoot("./example/js/"))
http.ListenAndServe(":8080", nil);

Or to enforce using the closure REST API:

cc := glosure.NewCompiler("./example/js/")
cc.UseClosureApi = true
http.Handle("/", glosure.GlosureServer(cc))
http.ListenAndServe(":8080", nil);

GlosureServer serves only the requests for compiled JavaScript (by default *.min.js) and returns error otherwise. For example, http://localhost:8080/sample.min.js returns the compiled version of ./example/js/sample.js, but dialing http://localhost:8080/sample.js results in a 404. You can change this behavior by setting a customized handler in cc.ErrorHandler.

For a more comprehensive example, take a look at example/server.go. You can run the example by:

# go run server.go --logtostderr -v=1

Documentation

Overview

Glosure is a convenient HTTP server for the Closure Compiler. It only responds to request for compiled JavaScript and returns error for any other requests.

Note: To force a compile on a request, pass request parameter "force=1".

Example
// Parse the flags if you want to use glog.
flag.Parse()

// Creat a new compiler assuming javascript files are in "example/js".
cc := NewCompiler("./example/js/")
// Use strict mode for the closure compiler. All warnings are treated as
// error.
cc.Strict()
// Or use debug mode.
// cc.Debug()

// Use advanced optimizations.
cc.CompilationLevel = AdvancedOptimizations

http.Handle("/", GlosureServer(cc))
fmt.Println("Checkout http://localhost:8080/sample.min.js")
http.ListenAndServe(":8080", nil)
Output:

Index

Examples

Constants

View Source
const (
	WhiteSpaceOnly        CompilationLevel = "WHITESPACE_ONLY"
	SimpleOptimizations                    = "SIMPLE_OPTIMIZATIONS"
	AdvancedOptimizations                  = "ADVANCED_OPTIMIZATIONS"
)
View Source
const (
	Quiet   WarningLevel = "QUIET"
	Default              = "DEFAULT"
	Verbose              = "VERBOSE"
)
View Source
const (
	EmcaScript3       Language = "ECMASCRIPT3"
	EmcaScript5                = "ECMASCRIPT5"
	EmcaScript5Strict          = "ECMASCRIPT5_STRICT"
)
View Source
const (
	AccessControls              = "accessControls"
	AmbiguousFunctionDecl       = "ambiguousFunctionDecl"
	CheckEventfulObjectDisposal = "checkEventfulObjectDisposal"
	CheckRegExp                 = "checkRegExp"
	CheckStructDictInheritance  = "checkStructDictInheritance"
	CheckTypes                  = "checkTypes"
	CheckVars                   = "checkVars"
	Const                       = "const"
	ConstantProperty            = "constantProperty"
	Deprecated                  = "deprecated"
	DuplicateMessage            = "duplicateMessage"
	Es3                         = "es3"
	Es5Strict                   = "es5Strict"
	ExternsValidation           = "externsValidation"
	FileoverviewTags            = "fileoverviewTags"
	GlobalThis                  = "globalThis"
	InternetExplorerChecks      = "internetExplorerChecks"
	InvalidCasts                = "invalidCasts"
	MisplacedTypeAnnotation     = "misplacedTypeAnnotation"
	MissingProperties           = "missingProperties"
	MissingProvide              = "missingProvide"
	MissingRequire              = "missingRequire"
	MissingReturn               = "missingReturn"
	NonStandardJsDocs           = "nonStandardJsDocs"
	ReportUnknownTypes          = "reportUnknownTypes"
	SuspiciousCode              = "suspiciousCode"
	StrictModuleDepCheck        = "strictModuleDepCheck"
	TypeInvalidation            = "typeInvalidation"
	UndefinedNames              = "undefinedNames"
	UndefinedVars               = "undefinedVars"
	UnknownDefines              = "unknownDefines"
	UselessCode                 = "uselessCode"
	Visibility                  = "visibility"
)
View Source
const DefaultCompiledSuffix = ".min.js"
View Source
const DefaultSourceSuffix = ".js"

Variables

This section is empty.

Functions

func GlosureServer

func GlosureServer(cc Compiler) http.Handler

Creates an http.Handler using the closure compiler.

func GlosureServerWithRoot

func GlosureServerWithRoot(root string) http.Handler

Creates a glosure http handler for the given root directory.

func ServeHttp

func ServeHttp(res http.ResponseWriter, req *http.Request, cc *Compiler)

Glosure's main handler function.

Types

type ClosureApiResult

type ClosureApiResult struct {
	CompiledCode string
	Errors       []ClosureError   `json:"errors"`
	Warnings     []ClosureWarning `json:"warnings"`
	ServerErrors []struct {
		Code  int    `json:"code"`
		Error string `json:"error"`
	} `json:"serverErrors"`
}

type ClosureError

type ClosureError struct {
	Charno    int
	Lineno    int
	File      string
	ErrorType string `json:"type"`
	Error     string
	Line      string
}

type ClosureWarning

type ClosureWarning struct {
	Charno      int
	Lineno      int
	File        string
	WarningType string `json:"type"`
	Warning     string
	Line        string
}

type CompilationLevel

type CompilationLevel string

type Compiler

type Compiler struct {
	// Path containing all JavaScript sources.
	Root string
	// Compiled JavaScript suffix. Uses ".min.js" by default.
	CompiledSuffix string
	// JavaScript source suffix. Uses ".js" by default.
	SourceSuffix string

	// Error handler.
	ErrorHandler http.HandlerFunc

	// Path of Closure's "compiler.jar". By default Glosure downloads the latest
	// compiler onto Compiler.Root.
	CompilerJarPath string

	// Compile source javascripts if not compiled or out of date.
	CompileOnDemand bool

	// Whether to use closure REST api instead of closure jar file. This is
	// automatically set to true when java is not installed on the machine.
	UseClosureApi bool

	// Closure compiler compilation level. Valid levels are: WhiteSpaceOnly,
	// SimpleOptimizations (default), AdvancedOptimizations.
	CompilationLevel CompilationLevel
	// Closure compiler warning level. Valid levels are: Quite, Default, and
	// Verbose.
	WarningLevel WarningLevel
	// Formatting of the compiled output. Valid formattings are: PrettyPrint,
	// and PrintInputDelimiter.
	Formatting Formatting
	// Whether to optimize out all unused JavaScript code.
	OnlyClosureDependencies bool

	// List of exern JavaScript files.
	Externs []string
	// Language
	Language Language
	// JavaScript files that should be included in every compilation.
	BaseFiles []string

	// Whether to perform an angular pass.
	AngularPass bool
	// Whether to process jQuery primitives.
	ProcessJqueryPrimitives bool

	// Warnings that should be treated as errors.
	CompErrors []WarningClass
	// Warnings.
	CompWarnings []WarningClass
	// Warnings that are suppressed.
	CompSuppressed []WarningClass
	// contains filtered or unexported fields
}

Compiler represents a contextual object for the closure compiler containing compilation options. To create a Compiler instance with default options use glosure.NewCompiler().

func NewCompiler

func NewCompiler(root string) Compiler

func (*Compiler) Compile

func (cc *Compiler) Compile(relOutPath string) error

func (*Compiler) CompileWithClosureApi

func (cc *Compiler) CompileWithClosureApi(jsFiles []string, entryPkgs []string,
	outPath string) error

func (*Compiler) CompileWithClosureJar

func (cc *Compiler) CompileWithClosureJar(jsFiles []string, entryPkgs []string,
	outPath string) error

func (*Compiler) Debug

func (cc *Compiler) Debug()

Enables options for debugger convenience.

func (*Compiler) Strict

func (cc *Compiler) Strict()

Enables strict compilation. Almost all warnings are treated as errors.

type Formatting

type Formatting string
const (
	PrettyPrint         Formatting = "pretty_print"
	PrintInputDelimiter            = "print_input_delimiter"
)

type Language

type Language string

type WarningClass

type WarningClass string

type WarningLevel

type WarningLevel string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL