配置Vite以支持在JS文件中使用JSX语法的方法
<p>Vite默认情况下不允许在.js文件中使用JSX语法。</p>
<p>我已经将我的文件重命名为<code>.jsx</code>(或<code>.tsx</code>),但是我有一些无法重命名的外部依赖。</p>
<p>Vite的错误示例:</p>
<pre class="brush:php;toolbar:false;">✘ [ERROR] 当前未启用JSX语法扩展
node_modules/somelib/src/someFile.js:122:11:
122 │ return <div/></pre>
<p>如何配置Vite以支持所有.js文件中的JSX表达式?</p>
您可以通过使用
loader选项将所有的js文件视为jsx来更改esbuild配置:// vite.config.ts import {defineConfig} from 'vite' // https://vitejs.dev/config/ export default defineConfig(() => ({ esbuild: { loader: "tsx", // OR "jsx" include: [ // Add this for business-as-usual behaviour for .jsx and .tsx files "src/**/*.jsx", "src/**/*.tsx", "node_modules/**/*.jsx", "node_modules/**/*.tsx", // Add the specific files you want to allow JSX syntax in "src/LocalJsxInJsComponent.js", "node_modules/bad-jsx-in-js-component/index.js", "node_modules/bad-jsx-in-js-component/js/BadJSXinJS.js", "node_modules/bad-jsx-in-js-component/ts/index.ts", "node_modules/bad-jsx-in-js-component/ts/BadTSXinTS.ts", // --- OR --- // Add these lines to allow all .js files to contain JSX "src/**/*.js", "node_modules/**/*.js", // Add these lines to allow all .ts files to contain JSX "src/**/*.ts", "node_modules/**/*.ts", ], }, }));注意:使用.jsx加载器加载.js文件会有性能损耗。
答案来自于Vite的GitHub上的这个讨论,将错误的(旧的)答案标记为“正确”。
更新于2023年3月
原始答案在
vite build中无法正常工作,只能在vite dev中正常工作。当前版本在vite@^4.0.0中两者都适用。您可以克隆并测试解决方案的示例仓库。