Skip to content

Plugin-React: Allow user provided babel plugins to be applied to non-project files  #16

@leebeydoun

Description

@leebeydoun

Clear and concise description of the problem

At present we can provide extra babel plugins to the @vitejs/plugin-react via its babel option, e.g:

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: ["@compiled/babel-plugin"],
      },
    }),
  ],
})

For the most part this works fine. The plugins provided are applied to project files, where a project file is not a node_module and starts with the projectRoot (project root being the current working directory). This is defined here

This is where I encounter an issue. I am using pnpm workspaces in my project and have a directory structure like:

root
|
|__vite-demo-app
|          vite.config.ts
|
|__packages/
|         |
|         |__ui-package/
|                    some-files.ts

During development my workspace packages use src/index.ts for their main entry-point in their package.json. This means when a file is loaded it needs to be transpiled (by vite in this case). In my case I am using @compiled/react which requires its babel
plugin to be applied before using the component. Since my packages will be outside the project-root the react-plugin will not apply the user provided plugins to it.

Suggested solution

Allow users to specify an include (or something similar) option which can be used to ensure that user provided plugins are still applied. For example, logic defined in the vite react plugin, could become:

const plugins = isProjectFile || options.include.some(match) ? [...userPlugins] : []

Then I could do something like:

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: ["@compiled/babel-plugin"],
        include: [function(filename) { return filename.includes('<my-project-name>/packages/<my-dep>'} ]
      },
    }),
  ],
})

The usage I'd ideally like to have seen is similar to how babel handles situations like this

Alternative

In my case I could pre-build my dependencies but this is not a great developer experience. Not aware of any other alternatives - but definitely open to suggestions.

My main goal in suggesting this change is so that I can make changes to workspace packages and see live reloads without needing to build the workspace package.

Additional context

Happy to pick this up myself and raise a PR for it.

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions