prettier/index.js

57 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-01-10 20:18:22 +03:00
"use strict";
2016-11-29 23:23:00 +03:00
const babylon = require("babylon");
const Printer = require("./src/printer").Printer;
const flowParser = require("flow-parser");
const comments = require("./src/comments");
2016-11-29 23:23:00 +03:00
var babylonOptions = {
sourceType: 'module',
allowImportExportEverywhere: false,
allowReturnOutsideFunction: false,
plugins: [
2017-01-10 22:18:39 +03:00
'jsx',
'flow',
2016-11-29 23:23:00 +03:00
'doExpressions',
2017-01-10 22:18:39 +03:00
'objectRestSpread',
'decorators',
'classProperties',
2016-11-29 23:23:00 +03:00
'exportExtensions',
2017-01-10 22:18:39 +03:00
'asyncGenerators',
2016-11-29 23:23:00 +03:00
'functionBind',
2017-01-10 22:18:39 +03:00
'functionSent',
'dynamicImport'
2016-11-29 23:23:00 +03:00
]
};
module.exports = {
2017-01-10 20:18:22 +03:00
format: function(text, opts) {
opts = opts || {};
let ast;
2016-11-29 23:23:00 +03:00
if(opts.useFlowParser) {
ast = flowParser.parse(text);
if(ast.errors.length > 0) {
let msg = ast.errors[0].message + " on line " + ast.errors[0].loc.start.line
if(opts.filename) {
msg += " in file " + opts.filename;
}
throw new Error(msg);
2016-12-30 21:32:43 +03:00
}
}
else {
ast = babylon.parse(text, babylonOptions);
2016-12-30 21:32:43 +03:00
}
2016-11-29 23:23:00 +03:00
// Interleave comment nodes
if(ast.comments) {
comments.attach(ast.comments, ast, text);
ast.comments = [];
}
ast.tokens = [];
opts.originalText = text;
const printer = new Printer(opts);
return printer.printGenerically(ast).code;
2016-11-29 23:23:00 +03:00
}
};