From 6453359852d4c93fe436bb94d73181eaa218b527 Mon Sep 17 00:00:00 2001 From: Evan You Date: Mon, 23 Aug 2021 12:20:53 -0400 Subject: [PATCH] feat(ref-transform): auto infer parser plugins --- packages/ref-transform/README.md | 6 +++++- packages/ref-transform/package.json | 5 +++-- packages/ref-transform/src/index.ts | 12 +++++++++++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/ref-transform/README.md b/packages/ref-transform/README.md index 45422555..e5ba22fb 100644 --- a/packages/ref-transform/README.md +++ b/packages/ref-transform/README.md @@ -60,7 +60,11 @@ const { } = transform(src, { filename: 'foo.ts', 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: [/* ... */] }) ``` diff --git a/packages/ref-transform/package.json b/packages/ref-transform/package.json index c6c4e1eb..0cebe3b3 100644 --- a/packages/ref-transform/package.json +++ b/packages/ref-transform/package.json @@ -28,10 +28,11 @@ }, "homepage": "https://github.com/vuejs/vue-next/tree/dev/packages/ref-transform#readme", "dependencies": { + "@babel/parser": "^7.15.0", "@vue/compiler-core": "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": { "@babel/core": "^7.15.0" diff --git a/packages/ref-transform/src/index.ts b/packages/ref-transform/src/index.ts index 21842746..73c5b086 100644 --- a/packages/ref-transform/src/index.ts +++ b/packages/ref-transform/src/index.ts @@ -63,9 +63,19 @@ export function transform( importHelpersFrom = 'vue' }: RefTransformOptions = {} ): 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, { sourceType: 'module', - plugins: [...babelParserDefaultPlugins, ...(parserPlugins || [])] + plugins: [...new Set([...babelParserDefaultPlugins, ...plugins])] }) const s = new MagicString(src) const res = transformAST(ast, s)