feat(ref-transform): auto infer parser plugins

This commit is contained in:
Evan You 2021-08-23 12:20:53 -04:00
parent 0805abe573
commit 6453359852
3 changed files with 19 additions and 4 deletions

View File

@ -60,7 +60,11 @@ const {
} = transform(src, { } = transform(src, {
filename: 'foo.ts', filename: 'foo.ts',
sourceMap: true, sourceMap: true,
parserPlugins: ['typescript']
// @babel/parser plugins to enable.
// 'typescript' and 'jsx' will be auto-inferred from filename if provided,
// so in most cases explicit parserPlugins are not necessary
parserPlugins: [/* ... */]
}) })
``` ```

View File

@ -28,10 +28,11 @@
}, },
"homepage": "https://github.com/vuejs/vue-next/tree/dev/packages/ref-transform#readme", "homepage": "https://github.com/vuejs/vue-next/tree/dev/packages/ref-transform#readme",
"dependencies": { "dependencies": {
"@babel/parser": "^7.15.0",
"@vue/compiler-core": "3.2.4", "@vue/compiler-core": "3.2.4",
"@vue/shared": "3.2.4", "@vue/shared": "3.2.4",
"@babel/parser": "^7.15.0", "estree-walker": "^2.0.2",
"estree-walker": "^2.0.2" "magic-string": "^0.25.7"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.15.0" "@babel/core": "^7.15.0"

View File

@ -63,9 +63,19 @@ export function transform(
importHelpersFrom = 'vue' importHelpersFrom = 'vue'
}: RefTransformOptions = {} }: RefTransformOptions = {}
): RefTransformResults { ): RefTransformResults {
const plugins: ParserPlugin[] = parserPlugins || []
if (filename) {
if (/\.tsx?$/.test(filename)) {
plugins.push('typescript')
}
if (filename.endsWith('x')) {
plugins.push('jsx')
}
}
const ast = parse(src, { const ast = parse(src, {
sourceType: 'module', sourceType: 'module',
plugins: [...babelParserDefaultPlugins, ...(parserPlugins || [])] plugins: [...new Set([...babelParserDefaultPlugins, ...plugins])]
}) })
const s = new MagicString(src) const s = new MagicString(src)
const res = transformAST(ast, s) const res = transformAST(ast, s)