diff --git a/packages/vant-cli/src/compiler/babel-preset-vue-ts.ts b/packages/vant-cli/src/compiler/babel-preset-vue-ts.ts new file mode 100644 index 000000000..c0a0fc45b --- /dev/null +++ b/packages/vant-cli/src/compiler/babel-preset-vue-ts.ts @@ -0,0 +1,26 @@ +/** + * @babel/preset-typescript 不支持编译 Vue 文件中的 ts 代码 + * 通过手动添加 @babel/plugin-transform-typescript 的方式来解决这个问题 + * see: https://github.com/babel/babel-loader/pull/738 + */ + +import { readFileSync } from 'fs'; +import { declare } from '@babel/helper-plugin-utils'; + +module.exports = declare(() => ({ + overrides: [ + { + test: (filePath: string) => { + if (/\.vue$/.test(filePath)) { + const template = readFileSync(filePath, { encoding: 'utf8' }); + return ( + template.includes('lang="ts"') || template.includes("lang='ts'") + ); + } + + return false; + }, + plugins: [require('@babel/plugin-transform-typescript')], + }, + ], +})); diff --git a/packages/vant-cli/src/config/babel.config.ts b/packages/vant-cli/src/config/babel.config.ts index 104b286a2..1e9a6e14f 100644 --- a/packages/vant-cli/src/config/babel.config.ts +++ b/packages/vant-cli/src/config/babel.config.ts @@ -18,6 +18,7 @@ module.exports = function (api?: ConfigAPI) { }, ], '@babel/preset-typescript', + require('../compiler/babel-preset-vue-ts'), ], plugins: [ [ diff --git a/packages/vant-cli/src/module.d.ts b/packages/vant-cli/src/module.d.ts index 99188db52..d18a11718 100644 --- a/packages/vant-cli/src/module.d.ts +++ b/packages/vant-cli/src/module.d.ts @@ -9,4 +9,5 @@ declare module 'release-it'; declare module 'html-webpack-plugin'; declare module 'conventional-changelog'; declare module '@vant/markdown-vetur'; +declare module '@babel/helper-plugin-utils'; declare module '@nuxt/friendly-errors-webpack-plugin';