import * as babel from '@babel/core' import * as sucrase from 'sucrase' import { ConeScaffoldProps } from './type' export function babelTsFile({ filepath, str, props = {}, }: { filepath: string str: string props: ConeScaffoldProps }): string { const { ts } = props if (!ts) { const result = babel.transformSync(str, { configFile: false, babelrc: false, // 这一行很关键, 不然文件行会乱 retainLines: true, filename: filepath, presets: [ [ require.resolve('@babel/preset-typescript'), { isTSX: true, allExtensions: true }, ], ], plugins: [require.resolve('@babel/plugin-syntax-jsx')], }) return (result && result.code) || str } return str } // sucrase 不能保留 jsx https://github.com/alangpierce/sucrase/issues/559 export function sucraseTsFile({ str, props = {}, }: { str: string props: ConeScaffoldProps }): string { const { ts } = props if (!ts) { const { code } = sucrase.transform(str, { transforms: ['jsx', 'typescript'], disableESTransforms: true, }) return code } return str }