Infer babel settings from file type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const recast = require('recast'); | |
const babylon = require('@babel/parser'); | |
function getParseCallOptions({ parse, ...parseOptions }) { | |
return { parse, parseOptions }; | |
} | |
function getPrintCallOptions({ print, ...printOptions }) { | |
return { print, printOptions }; | |
} | |
class AutoParserBabylon { | |
static get supportedFileTypes() { | |
return { | |
'.js': {}, | |
'.cjs': {}, | |
'.mjs': {}, | |
'.json': { parse: babylon.parseExpression }, | |
'.ts': { parseOptions: { plugins: ['typescript'] } }, | |
'.jsx': { parseOptions: { plugins: ['jsx'] } }, | |
'.tsx': { parseOptions: { plugins: ['jsx', 'typescript'] } }, | |
'.js.flow': { parseOptions: { plugins: ['flow'] } }, | |
'.json.flow': { parse: babylon.parseExpression, parseOptions: { plugins: ['flow'] } }, | |
}; | |
} | |
static mergeOptions(aOptions, bOptions) { | |
return { | |
parseOptions: { | |
...aOptions.parseOptions, | |
...bOptions.parseOptions, | |
plugins: [ | |
...(aOptions.parseOptions ? aOptions.parseOptions.plugins || [] : []), | |
...(bOptions.parseOptions ? bOptions.parseOptions.plugins || [] : []), | |
], | |
}, | |
printOptions: { | |
...aOptions.printOptions, | |
...bOptions.printOptions, | |
}, | |
}; | |
} | |
constructor(options = {}) { | |
const { mergeOptions } = this.constructor; | |
this.options = mergeOptions(options, { parseOptions: { tokens: true } }); | |
} | |
parse(content, options) { | |
const { mergeOptions } = this.constructor; | |
const { parse = babylon.parse, parseOptions } = mergeOptions( | |
this.options, | |
getParseCallOptions(options), | |
); | |
return recast.parse(content, { | |
parser: { | |
parse: (source) => { | |
return parse(source, parseOptions); | |
}, | |
}, | |
}); | |
} | |
print(ast, options) { | |
const { print = recast.print, printOptions } = this.mergeOptions( | |
this.options, | |
getPrintCallOptions(options), | |
); | |
return print(ast, printOptions); | |
} | |
} | |
module.exports = MacromeParserBabylon; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment