Framework
Version

使用 Webpack 安裝

要在 Webpack 中使用基於檔案的路由 (file-based routing),您需要安裝 @tanstack/router-plugin 套件。

sh
npm install -D @tanstack/router-plugin
npm install -D @tanstack/router-plugin

安裝完成後,您需要將插件加入設定檔中。

tsx
// webpack.config.ts
import { TanStackRouterWebpack } from '@tanstack/router-plugin/webpack'

export default {
  plugins: [
    TanStackRouterWebpack({ target: 'react', autoCodeSplitting: true }),
  ],
}
// webpack.config.ts
import { TanStackRouterWebpack } from '@tanstack/router-plugin/webpack'

export default {
  plugins: [
    TanStackRouterWebpack({ target: 'react', autoCodeSplitting: true }),
  ],
}

或者,您可以複製我們的 快速開始 Webpack 範例 直接開始使用。

現在您已將插件加入 Webpack 設定,接下來就可以開始使用 TanStack Router 的基於檔案路由功能。

忽略自動生成的路由樹檔案

如果您的專案配置了程式碼檢查工具 (linter) 或格式化工具 (formatter),您可能需要忽略自動生成的 routeTree.gen.ts 檔案。此檔案由 TanStack Router 管理,因此不應被您的檢查工具或格式化工具修改。

以下是一些幫助您忽略該檔案的資源:

Warning

如果您使用 VSCode,在重新命名路由後,可能會遇到路由樹檔案意外開啟(並顯示錯誤)的情況。

您可以透過 VSCode 設定將該檔案標記為唯讀來避免此問題。我們建議同時透過以下設定將其從搜尋結果和檔案監控中排除:

json
{
  "files.readonlyInclude": {
    "**/routeTree.gen.ts": true
  },
  "files.watcherExclude": {
    "**/routeTree.gen.ts": true
  },
  "search.exclude": {
    "**/routeTree.gen.ts": true
  }
}
{
  "files.readonlyInclude": {
    "**/routeTree.gen.ts": true
  },
  "files.watcherExclude": {
    "**/routeTree.gen.ts": true
  },
  "search.exclude": {
    "**/routeTree.gen.ts": true
  }
}

您可以在使用者層級或僅針對單一工作區使用這些設定,只需在專案根目錄建立 .vscode/settings.json 檔案即可。

配置設定

當使用 TanStack Router Plugin 搭配 Webpack 進行基於檔案的路由時,它提供了一些適合多數專案的預設值:

json
{
  "routesDirectory": "./src/routes",
  "generatedRouteTree": "./src/routeTree.gen.ts",
  "routeFileIgnorePrefix": "-",
  "quoteStyle": "single"
}
{
  "routesDirectory": "./src/routes",
  "generatedRouteTree": "./src/routeTree.gen.ts",
  "routeFileIgnorePrefix": "-",
  "quoteStyle": "single"
}

如果這些預設值符合您的專案需求,您無需進行任何配置!但如果您需要自定義配置,可以透過編輯傳入 TanStackRouterWebpack 函式的配置物件來實現。

您可以在 基於檔案路由 API 參考文件 中找到所有可用的配置選項。

Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.