Skip to content

Commit

Permalink
feat(plugin-react): let Vite plugins define Babel plugins/presets
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Oct 29, 2021
1 parent 1248b62 commit c655ef1
Showing 1 changed file with 37 additions and 7 deletions.
44 changes: 37 additions & 7 deletions packages/plugin-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ import {
import { babelImportToRequire } from './jsx-runtime/babel-import-to-require'
import { restoreJSX } from './jsx-runtime/restore-jsx'

declare module 'vite' {
export interface Plugin {
/**
* Babel configuration applied in both dev and prod.
*/
babel?: Pick<TransformOptions, 'plugins' | 'presets'>
}
}

export interface Options {
include?: string | RegExp | Array<string | RegExp>
exclude?: string | RegExp | Array<string | RegExp>
Expand Down Expand Up @@ -54,7 +63,9 @@ export default function viteReact(opts: Options = {}): PluginOption[] {

const useAutomaticRuntime = opts.jsxRuntime !== 'classic'

const userPlugins = opts.babel?.plugins || []
let userPlugins = [...(opts.babel?.plugins || [])]
let userPresets = [...(opts.babel?.presets || [])]

const userParserPlugins =
opts.parserPlugins || opts.babel?.parserOpts?.plugins || []

Expand Down Expand Up @@ -88,15 +99,33 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
)
}

config.plugins.forEach(
(plugin) =>
(plugin.name === 'react-refresh' ||
(plugin !== viteReactJsx && plugin.name === 'vite:react-jsx')) &&
config.logger.warn(
config.plugins.forEach((plugin) => {
const isExtraneous =
plugin.name === 'react-refresh' ||
(plugin !== viteReactJsx && plugin.name === 'vite:react-jsx')

if (isExtraneous)
return config.logger.warn(
`[@vitejs/plugin-react] You should stop using "${plugin.name}" ` +
`since this plugin conflicts with it.`
)
)

if (plugin.babel) {
const { plugins, presets } = plugin.babel
if (plugins) {
userPlugins =
plugin.enforce === 'pre'
? [...plugins, ...userPlugins]
: [...userPlugins, ...plugins]
}
if (presets) {
userPresets =
plugin.enforce === 'pre'
? [...presets, ...userPresets]
: [...userPresets, ...presets]
}
}
})
},
async transform(code, id, options) {
const ssr = typeof options === 'boolean' ? options : options?.ssr === true
Expand Down Expand Up @@ -212,6 +241,7 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
decoratorsBeforeExport: true
},
plugins,
presets: userPresets,
sourceMaps: true,
// Vite handles sourcemap flattening
inputSourceMap: false as any
Expand Down

0 comments on commit c655ef1

Please sign in to comment.