Skip to content

Instantly share code, notes, and snippets.

@conartist6
Created March 6, 2021 15:47
Embed
What would you like to do?
Infer babel settings from file type
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