42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import * as babel from "@babel/core"
|
|
import type { PluginOption, TransformResult } from "vite"
|
|
|
|
const sourceRegex = /\.(j|t)sx?$/
|
|
|
|
export default function macrosPlugin(): PluginOption {
|
|
return {
|
|
name: "babel-macros",
|
|
enforce: "pre",
|
|
transform(source: string, filename: string) {
|
|
if (filename.includes("node_modules")) {
|
|
return undefined
|
|
}
|
|
if (!sourceRegex.test(filename)) {
|
|
return
|
|
}
|
|
const hasBabelMacro = source.includes('.macro"')
|
|
const hasEmotion = source.includes("@emotion")
|
|
if (!hasBabelMacro && !hasEmotion) {
|
|
return undefined
|
|
}
|
|
const result = babel.transformSync(source, {
|
|
filename,
|
|
parserOpts: {
|
|
plugins: ["jsx", "typescript", "decorators-legacy"],
|
|
},
|
|
plugins: [
|
|
hasBabelMacro && require.resolve("babel-plugin-macros"),
|
|
hasEmotion && require.resolve("@emotion/babel-plugin"),
|
|
].filter(Boolean),
|
|
generatorOpts: {
|
|
decoratorsBeforeExport: true,
|
|
},
|
|
babelrc: false,
|
|
configFile: false,
|
|
sourceMaps: true,
|
|
})
|
|
return result as TransformResult | null
|
|
},
|
|
}
|
|
}
|