Improve auto-import for JSX (the `jsxInject` option)
See original GitHub issueIs your feature request related to a problem? Please describe.
According to the document of Vite, we can do an auto-import
for JSX by:
// vite.config.js
export default {
esbuild: {
jsxInject: `import React from 'react'`
}
}
But it just places this snippet to the header of codes by simply concatenating string:
If some codes have already import React for something like:
import React from 'react';
export default function Button(props: React.ButtonHTMLAttributes<HTMLElement>) {
return <div {...props} />
}
that will cause conflict and throw an error: Uncaught SyntaxError: Identifier 'React' has already been declared
.
I know some codemod can migrate the React imports, but I don’t want to change that codes for some reason.
Describe the solution you’d like
According to the document of ESBuild:
First, create a file called react-shim.js that re-exports everything from the react package in an export called React:
// react-shim.js
export * as React from 'react'
Then use esbuild’s inject feature to inject this into each file:
esbuild app.jsx --bundle --inject:./react-shim.js --outfile=out.js
In my test, I create a file with:
import React from 'react';
export default function Test() {
return <div>Test</div>
}
Then use esbuild’s inject feature by --inject:./react-shim.js
, esbuild will output:
import * as React from "react";
import React2 from "react";
export default function Test() {
return /* @__PURE__ */ React2.createElement("div", null, "Test");
}
Although there are duplicate variables React
, but at least this is compatible with the old code.
So I hope vite
can provide inject
config of esbuild
.
Describe alternatives you’ve considered
Or handle duplicated import by vite
itself.
Additional context
Some codemod
can migrate the React importing:
https://github.com/reactjs/react-codemod#update-react-imports
Issue Analytics
- State:
- Created 3 years ago
- Reactions:7
- Comments:10 (4 by maintainers)
Top GitHub Comments
Now that
vite-react-jsx
exists, theesbuild.jsxInject
option will probably be deprecated.Considering the following snippet: https://github.com/vitejs/vite/blob/a0d922e7d9790f998c246f8122bc339717b6088f/packages/vite/src/node/plugins/esbuild.ts#L125
Why not just make jsxInject a function that you pass result.code into? What I’m proposing is something like:
The refactoring changes would be minimal, the old way of directly passing a string can still be supported and it adds more flexibility to the configuration IMO.