本文整理汇总了Java中com.google.javascript.jscomp.Compiler.initOptions方法的典型用法代码示例。如果您正苦于以下问题:Java Compiler.initOptions方法的具体用法?Java Compiler.initOptions怎么用?Java Compiler.initOptions使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.javascript.jscomp.Compiler
的用法示例。
在下文中一共展示了Compiler.initOptions方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: compileFiles
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
@SuppressWarnings("deprecation")
private OOPSourceCodeModel compileFiles(List<RawFile> files, List<String> projectFileTypes) {
OOPSourceCodeModel model = new OOPSourceCodeModel();
for (RawFile file : files) {
try {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
options.setIdeMode(true);
options.setParseJsDocDocumentation(JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE);
compiler.initOptions(options);
Node root = new JsAst(SourceFile.fromCode(file.name(), file.content())).getAstRoot(compiler);
JavaScriptListener jsListener = new JavaScriptListener(model, file, projectFileTypes);
NodeTraversal.traverseEs6(compiler, root, jsListener);
} catch (Exception e) {
e.printStackTrace();
}
}
return model;
}
示例2: testPropType
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
private void testPropType(String reactPropType, String typeExpression) {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
// So that source dumps still have JSDoc
options.preserveTypeAnnotations = true;
compiler.initOptions(options);
// Avoid extra "use strict" boilerplate in output.
options.setEmitUseStrict(false);
compiler.disableThreads(); // Makes errors easier to track down.
Node reactPropTypeNode = compiler.parse(
SourceFile.fromCode("/src/test.js", reactPropType))
.getFirstChild().getFirstChild();
assertArrayEquals(new JSError[]{}, compiler.getErrors());
Node typeNode = PropTypesExtractor.convertPropType(reactPropTypeNode)
.typeNode;
// Easiest way to stringify the type node is to print it out as JSDoc.
JSDocInfoBuilder jsDocInfoBuilder = new JSDocInfoBuilder(true);
jsDocInfoBuilder.recordType(new JSTypeExpression(
typeNode, "/src/test.js"));
Node tempNode = IR.var(IR.name("temp"));
tempNode.setJSDocInfo(jsDocInfoBuilder.build());
String tempCode = compiler.toSource(tempNode);
assertEquals("/** @type {" + typeExpression + "} */ var temp", tempCode);
}
示例3: process
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
@Override
public String process(File[] srcFiles) throws ProcessException {
CompilerOptions compilerOptions = new CompilerOptions();
compilerOptions.setCodingConvention(new ClosureCodingConvention());
compilerOptions.setOutputCharset("UTF-8");
compilerOptions.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.WARNING);
compilerOptions.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT5);
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(compilerOptions);
Compiler compiler = new Compiler();
compiler.disableThreads();
compiler.initOptions(compilerOptions);
ArrayList<SourceFile> inputFiles = new ArrayList<SourceFile>();
for (File srcFile : srcFiles) {
SourceFile inputFile = SourceFile.fromFile(srcFile);
inputFiles.add(inputFile);
}
Result result = compiler.compile(new ArrayList<SourceFile>(), inputFiles, compilerOptions);
if (!result.success) {
throw new ProcessException("Failure when processing javascript files!");
}
return compiler.toSource();
}
示例4: process
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
@Override
public void process(final Reader reader, final Writer writer) throws IOException {
logger.debug("google closure processing...");
final String originalJsSourceCode = IOUtils.toString(reader);
try {
Compiler.setLoggingLevel(Level.SEVERE);
final Compiler compiler = new Compiler();
final CompilerOptions compilerOptions = newCompilerOptions();
compilationLevel.setOptionsForCompilationLevel(compilerOptions);
//make it play nice with GAE
compiler.disableThreads();
compiler.initOptions(compilerOptions);
final SourceFile input = SourceFile.fromInputStream("dummy.js", new ByteArrayInputStream(originalJsSourceCode.getBytes(soyViewConf.globalEncoding())));
final Result result = compiler.compile(Lists.<SourceFile>newArrayList(), Lists.newArrayList(input), compilerOptions);
logWarningsAndErrors(result);
boolean origFallback = false;
if (result.success) {
final String minifiedJsSourceCode = compiler.toSource();
if (StringUtils.isEmpty(minifiedJsSourceCode)) {
origFallback = true;
} else {
writer.write(minifiedJsSourceCode);
}
} else {
origFallback = true;
}
if (origFallback) {
writer.write(originalJsSourceCode);
}
} finally {
reader.close();
writer.close();
}
}
示例5: parse
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
private Node parse(String source, String expected, LanguageMode languageIn) {
CompilerOptions options = new CompilerOptions();
options.setLanguageIn(languageIn);
options.setLanguageOut(LanguageMode.ECMASCRIPT6_TYPED);
options.setPreserveTypeAnnotations(true);
options.setPrettyPrint(true);
options.setLineLengthThreshold(80);
options.setPreferSingleQuotes(true);
Compiler compiler = new Compiler();
compiler.setErrorManager(testErrorManager);
compiler.initOptions(options);
Node script = compiler.parse(SourceFile.fromCode("[test]", source));
// Verifying that all warnings were seen
assertTrue("Missing an error", testErrorManager.hasEncounteredAllErrors());
assertTrue("Missing a warning", testErrorManager.hasEncounteredAllWarnings());
if (script != null && testErrorManager.getErrorCount() == 0) {
// if it can be parsed, it should round trip.
String actual = new CodePrinter.Builder(script)
.setCompilerOptions(options)
.setTypeRegistry(compiler.getTypeIRegistry())
.build() // does the actual printing.
.trim();
assertThat(actual).isEqualTo(expected);
}
return script;
}
示例6: process
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
@Override
public String process(final String filename, final String source, final Config conf)
throws Exception {
final CompilerOptions copts = new CompilerOptions();
copts.setCodingConvention(new ClosureCodingConvention());
copts.setOutputCharset("UTF-8");
copts.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.WARNING);
CompilationLevel level = level(get("level"));
level.setOptionsForCompilationLevel(copts);
Compiler.setLoggingLevel(Level.SEVERE);
Compiler compiler = new Compiler();
compiler.disableThreads();
compiler.initOptions(copts);
List<SourceFile> externs = externs(copts);
Result result = compiler.compile(externs,
ImmutableList.of(SourceFile.fromCode(filename, source)), copts);
if (result.success) {
return compiler.toSource();
}
List<AssetProblem> errors = Arrays.stream(result.errors)
.map(error -> new AssetProblem(error.sourceName, error.lineNumber, error.getCharno(),
error.description, null))
.collect(Collectors.toList());
throw new AssetException(name(), errors);
}
示例7: computeDepInfo
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
@VisibleForTesting
static ImmutableMap<Source, Metadata<DepInfo>> computeDepInfo(
Log log,
ImmutableMap<Source, Metadata<DepInfo>> oldDepInfoMap,
JsOptions options,
Function<Source, ByteSource> loader,
Iterable<? extends Source> sources)
throws IOException {
final Compiler parsingCompiler = new Compiler(
new MavenLogJSErrorManager(log));
parsingCompiler.initOptions(options.toCompilerOptions());
return SourceMetadataMapBuilder.updateFromSources(
oldDepInfoMap,
loader,
new Extractor<DepInfo>() {
@Override
public DepInfo extractMetadata(Source source, byte[] content)
throws IOException {
String code = new String(content, Charsets.UTF_8);
SourceFile sourceFile = new SourceFile.Builder()
.withCharset(Charsets.UTF_8)
.withOriginalPath(source.relativePath.getPath())
.buildFromCode(source.canonicalPath.getPath(), code);
CompilerInput inp = new CompilerInput(sourceFile);
inp.setCompiler(parsingCompiler);
Collection<String> provides = inp.getProvides();
Collection<String> requires = inp.getRequires();
if (provides.isEmpty() && requires.isEmpty()) {
// closure/goog/base.js provides basic definitions for things like
// goog.require and goog.provide.
// Anything that calls a goog.* method implicitly requires goog.
// closure/goog/base.js gets around this by using the special
// "@provideGoog" annotation.
// That seems to be specially handled by JSCompiler but not via
// the CompilerInput API.
CStyleLexer lexer = new CStyleLexer(
sourceFile.getCode(),
true /* Need doc comments. */);
for (CStyleLexer.Token headerToken : lexer) {
if (headerToken.type != CStyleLexer.TokenType.DOC_COMMENT) {
break;
}
if (headerToken.containsText("@provideGoog")) {
provides = ImmutableSet.of("goog");
break;
}
}
}
return new DepInfo(
inp.isModule(),
inp.getName(),
googNamespaces(provides),
googNamespaces(requires));
}
},
sources);
}
示例8: outputSource
import com.google.javascript.jscomp.Compiler; //导入方法依赖的package包/类
/**
* Outputs the source equivalent of the abstract syntax tree, optionally generating a sourcemap.
*
* @param node The JavaScript abstract syntax tree.
* @param outputFormat The source output format options.
* @param inputFileName The source file name to associate with the input node, used for sourcemap
* generation.
* @param inputSourceMap The content of the input sourcemap.
* @param sourceMapOutputFileName The name of the output sourcemap.
* @return The equivalent JavaScript source.
*/
private static String outputSource(
Node node,
ImmutableSet<OutputFormat> outputFormat,
String inputFileName,
String inputSourceMap,
String sourceMapOutputFileName) {
CompilerOptions options = new CompilerOptions();
options.setPrettyPrint(outputFormat.contains(OutputFormat.PRETTY));
options.setPreferSingleQuotes(outputFormat.contains(OutputFormat.SINGLE_QUOTE_STRINGS));
// The Closure Compiler treats the 'use strict' directive as a property of a node. CodeBuilder
// doesn't consider directives during its code generation. Instead, it inserts the 'use strict'
// directive if it is in a strict language mode.
Set<String> directives = node.getDirectives();
if ((directives != null) && directives.contains("use strict")) {
options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT_2015);
options.setEmitUseStrict(true);
}
options.skipAllCompilerPasses();
if (inputSourceMap != null) {
SourceFile sourceMapSourceFile = SourceFile.fromCode("input.sourcemap", inputSourceMap);
ImmutableMap<String, SourceMapInput> inputSourceMaps =
ImmutableMap.of(inputFileName, new SourceMapInput(sourceMapSourceFile));
options.setInputSourceMaps(inputSourceMaps);
options.setApplyInputSourceMaps(true);
// Simply setting the path to any non-null value will trigger source map generation.
// Since sourceMapOutputPath is handled by AbstractCommandLineRunner and not the Compiler
// itself, we manually output the final sourcemap below.
options.setSourceMapOutputPath("/dev/null");
}
Compiler compiler = new Compiler();
compiler.disableThreads();
compiler.initOptions(options);
compiler.initBasedOnOptions();
Compiler.CodeBuilder cb = new Compiler.CodeBuilder();
compiler.toSource(cb, 0, node);
if (inputFileName != null && inputSourceMap != null && sourceMapOutputFileName != null) {
try {
FileOutputStream fileOut = new FileOutputStream(sourceMapOutputFileName);
OutputStreamWriter out = new OutputStreamWriter(fileOut, UTF_8);
compiler.getSourceMap().appendTo(out, "renamed.js");
out.close();
} catch (Exception e) {
System.err.println(e + "Error writing output sourcemap.");
}
}
return cb.toString();
}