Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(plugin-react): allow options.babel to be a function #6238

Merged
merged 4 commits into from
May 20, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 61 additions & 17 deletions packages/plugin-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ export interface Options {
/**
* Babel configuration applied in both dev and prod.
*/
babel?: BabelOptions
babel?:
| BabelOptions
| ((id: string, options: { ssr?: boolean }) => BabelOptions)
cyco130 marked this conversation as resolved.
Show resolved Hide resolved
}

export type BabelOptions = Omit<
Expand All @@ -59,6 +61,8 @@ export type BabelOptions = Omit<
* an `api.reactBabel` method.
*/
export interface ReactBabelOptions extends BabelOptions {
ssr?: boolean
file: string
cyco130 marked this conversation as resolved.
Show resolved Hide resolved
plugins: Extract<BabelOptions['plugins'], any[]>
presets: Extract<BabelOptions['presets'], any[]>
overrides: Extract<BabelOptions['overrides'], any[]>
Expand All @@ -67,13 +71,18 @@ export interface ReactBabelOptions extends BabelOptions {
}
}

type ReactBabelHook = (
options: ReactBabelOptions,
config: ResolvedConfig
) => void

declare module 'vite' {
export interface Plugin {
api?: {
/**
* Manipulate the Babel options of `@vitejs/plugin-react`
*/
reactBabel?: (options: ReactBabelOptions, config: ResolvedConfig) => void
reactBabel?: ReactBabelHook
}
}
}
Expand All @@ -86,21 +95,11 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
let projectRoot = process.cwd()
let skipFastRefresh = opts.fastRefresh === false
let skipReactImport = false
let runPluginOverrides = (options: ReactBabelOptions) => false
let staticBabelOptions: ReactBabelOptions | undefined

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

const babelOptions = {
babelrc: false,
configFile: false,
...opts.babel
} as ReactBabelOptions

babelOptions.plugins ||= []
babelOptions.presets ||= []
babelOptions.overrides ||= []
babelOptions.parserOpts ||= {} as any
babelOptions.parserOpts.plugins ||= []

// Support patterns like:
// - import * as React from 'react';
// - import React from 'react';
Expand Down Expand Up @@ -141,11 +140,22 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
`[@vitejs/plugin-react] You should stop using "${plugin.name}" ` +
`since this plugin conflicts with it.`
)
})

runPluginOverrides = (babelOptions) => {
const hooks = config.plugins
.map((plugin) => plugin.api?.reactBabel)
.filter(Boolean) as ReactBabelHook[]
cyco130 marked this conversation as resolved.
Show resolved Hide resolved

if (plugin.api?.reactBabel) {
plugin.api.reactBabel(babelOptions, config)
if (hooks.length > 0) {
return (runPluginOverrides = (babelOptions) => {
hooks.forEach((hook) => hook(babelOptions, config))
return true
})(babelOptions)
}
})
runPluginOverrides = () => false
return false
}
},
async transform(code, id, options) {
const ssr = typeof options === 'boolean' ? options : options?.ssr === true
Expand All @@ -162,6 +172,18 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
const isProjectFile =
!isNodeModules && (id[0] === '\0' || id.startsWith(projectRoot + '/'))

let babelOptions = staticBabelOptions
if (typeof opts.babel === 'function') {
const rawOptions = opts.babel(id, { ssr })
babelOptions = createBabelOptions(id, rawOptions, ssr)
runPluginOverrides(babelOptions)
} else if (!babelOptions) {
babelOptions = createBabelOptions(id, opts.babel, ssr)
if (!runPluginOverrides(babelOptions)) {
staticBabelOptions = babelOptions
cyco130 marked this conversation as resolved.
Show resolved Hide resolved
}
}

const plugins = isProjectFile ? [...babelOptions.plugins] : []

let useFastRefresh = false
Expand Down Expand Up @@ -368,3 +390,25 @@ viteReact.preambleCode = preambleCode
function loadPlugin(path: string): Promise<any> {
return import(path).then((module) => module.default || module)
}

function createBabelOptions(
file: string,
rawOptions?: BabelOptions,
ssr?: boolean
) {
const babelOptions = {
ssr,
file,
Copy link
Member

@aleclarson aleclarson May 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option is to use Object.defineProperties to define ssr and file options with enumerable: false (note this is the default when using defineProperties). That will prevent Babel from getting them, since non-enumerable properties are ignored by the spread operator.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel the intention would be less obvious and require a comment. But I can do that if you feel it'd be better.

Copy link
Member

@patak-dev patak-dev May 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these in the same object? I think the API would be more clear with three args. ssr and file are quite different than the rest of the object

type ReactBabelHook = (
  babelConfig: ReactBabelOptions,
  options: { ssr, file }, // or context?
  config: ResolvedConfig
) => void

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok let's do that, and I vote context as the name

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the changes @cyco130!

Sorry, one last question 👀
Why is it called file? Now that it is in the second parameter, should we rename it to id? file isn't that good in case there are virtual modules, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed (wasn't my idea anyway :P )

babelrc: false,
configFile: false,
...rawOptions
} as ReactBabelOptions

babelOptions.plugins ||= []
babelOptions.presets ||= []
babelOptions.overrides ||= []
babelOptions.parserOpts ||= {} as any
babelOptions.parserOpts.plugins ||= []

return babelOptions
}