搜尋

首頁  >  問答  >  主體

配置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>
P粉571233520P粉571233520581 天前788

全部回覆(1)我來回復

  • P粉877719694

    P粉8777196942023-08-25 14:42:21

    您可以透過使用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中兩者都適用。

    您可以複製並測試解決方案的範例倉庫

    回覆
    0
  • 取消回覆