Selaa lähdekoodia

docs: Add docs on vite plugin usage

Michael Bromley 2 kuukautta sitten
vanhempi
sitoutus
8ccd2557ea

+ 16 - 0
docs/docs/guides/extending-the-dashboard/getting-started/index.md

@@ -124,6 +124,22 @@ to correctly resolve imports of GraphQL types & interpret JSX in your dashboard
 }
 ```
 
+### Monorepo Setup
+
+If your project uses a monorepo structure, such as with Nx or Turborepo, then you'll need to make some adjustments
+to the paths given above:
+
+If each Vendure plugin is its own "package", outside the main Vendure server app, then it would need its own
+tsconfig for each plugin package. You might run into errors like:
+
+```
+Error loading Vendure config: Cannot find module
+```
+
+In this case, you'll need to configure a [PathAdapter](/reference/dashboard/vite-plugin/vendure-dashboard-plugin#pathadapter).
+
+You should also put your `vite.config.mts` file into the Vendure app directory rather than the root.
+
 ## The DashboardPlugin
 
 In your `vendure-config.ts` file, you should also import and configure the [DashboardPlugin](/reference/core-plugins/dashboard-plugin/).

+ 14 - 0
docs/docs/reference/dashboard/vite-plugin/index.md

@@ -0,0 +1,14 @@
+---
+title: "Vite Plugin"
+isDefaultIndex: true
+generated: true
+---
+<!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script -->
+import MemberInfo from '@site/src/components/MemberInfo';
+import GenerationInfo from '@site/src/components/GenerationInfo';
+import MemberDescription from '@site/src/components/MemberDescription';
+
+
+import DocCardList from '@theme/DocCardList';
+
+<DocCardList />

+ 347 - 0
docs/docs/reference/dashboard/vite-plugin/vendure-dashboard-plugin.md

@@ -0,0 +1,347 @@
+---
+title: "VendureDashboardPlugin"
+isDefaultIndex: false
+generated: true
+---
+<!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script -->
+import MemberInfo from '@site/src/components/MemberInfo';
+import GenerationInfo from '@site/src/components/GenerationInfo';
+import MemberDescription from '@site/src/components/MemberDescription';
+
+
+## vendureDashboardPlugin
+
+<GenerationInfo sourceFile="packages/dashboard/vite/vite-plugin-vendure-dashboard.ts" sourceLine="154" packageName="@vendure/dashboard" since="3.4.0" />
+
+This is the Vite plugin which powers the Vendure Dashboard, including:
+
+- Configuring routing, styling and React support
+- Analyzing your VendureConfig file and introspecting your schema
+- Loading your custom Dashboard extensions
+
+```ts title="Signature"
+function vendureDashboardPlugin(options: VitePluginVendureDashboardOptions): PluginOption[]
+```
+Parameters
+
+### options
+
+<MemberInfo kind="parameter" type={`<a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#vitepluginvenduredashboardoptions'>VitePluginVendureDashboardOptions</a>`} />
+
+
+
+## VitePluginVendureDashboardOptions
+
+<GenerationInfo sourceFile="packages/dashboard/vite/vite-plugin-vendure-dashboard.ts" sourceLine="31" packageName="@vendure/dashboard" since="3.4.0" />
+
+Options for the <a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#venduredashboardplugin'>vendureDashboardPlugin</a> Vite plugin.
+
+```ts title="Signature"
+type VitePluginVendureDashboardOptions = {
+    /**
+     * @description
+     * The path to the Vendure server configuration file.
+     */
+    vendureConfigPath: string | URL;
+    /**
+     * @description
+     * The {@link PathAdapter} allows you to customize the resolution of paths
+     * in the compiled Vendure source code which is used as part of the
+     * introspection step of building the dashboard.
+     *
+     * It enables support for more complex repository structures, such as
+     * monorepos, where the Vendure server configuration file may not
+     * be located in the root directory of the project.
+     *
+     * If you get compilation errors like "Error loading Vendure config: Cannot find module",
+     * you probably need to provide a custom `pathAdapter` to resolve the paths correctly.
+     *
+     * @example
+     * ```ts
+     * vendureDashboardPlugin({
+     *     tempCompilationDir: join(__dirname, './__vendure-dashboard-temp'),
+     *     pathAdapter: {
+     *         getCompiledConfigPath: ({ inputRootDir, outputPath, configFileName }) => {
+     *             const projectName = inputRootDir.split('/libs/')[1].split('/')[0];
+     *             const pathAfterProject = inputRootDir.split(`/libs/${projectName}`)[1];
+     *             const compiledConfigFilePath = `${outputPath}/${projectName}${pathAfterProject}`;
+     *             return path.join(compiledConfigFilePath, configFileName);
+     *         },
+     *         transformTsConfigPathMappings: ({ phase, patterns }) => {
+     *             // "loading" phase is when the compiled Vendure code is being loaded by
+     *             // the plugin, in order to introspect the configuration of your app.
+     *             if (phase === 'loading') {
+     *                 return patterns.map((p) =>
+     *                     p.replace('libs/', '').replace(/.ts$/, '.js'),
+     *                 );
+     *             }
+     *             return patterns;
+     *         },
+     *     },
+     *     // ...
+     * }),
+     * ```
+     */
+    pathAdapter?: PathAdapter;
+    /**
+     * @description
+     * The name of the exported variable from the Vendure server configuration file, e.g. `config`.
+     * This is only required if the plugin is unable to auto-detect the name of the exported variable.
+     */
+    vendureConfigExport?: string;
+    /**
+     * @description
+     * The path to the directory where the generated GraphQL Tada files will be output.
+     */
+    gqlOutputPath?: string;
+    tempCompilationDir?: string;
+    /**
+     * @description
+     * Allows you to customize the location of node_modules & glob patterns used to scan for potential
+     * Vendure plugins installed as npm packages. If not provided, the compiler will attempt to guess
+     * the location based on the location of the `@vendure/core` package.
+     */
+    pluginPackageScanner?: PackageScannerConfig;
+    /**
+     * @description
+     * Allows you to selectively disable individual plugins.
+     * @example
+     * ```ts
+     * vendureDashboardPlugin({
+     *   vendureConfigPath: './config.ts',
+     *   disablePlugins: {
+     *     react: true,
+     *     lingui: true,
+     *   }
+     * })
+     * ```
+     */
+    disablePlugins?: {
+        tanstackRouter?: boolean;
+        react?: boolean;
+        lingui?: boolean;
+        themeVariables?: boolean;
+        tailwindSource?: boolean;
+        tailwindcss?: boolean;
+        configLoader?: boolean;
+        viteConfig?: boolean;
+        adminApiSchema?: boolean;
+        dashboardMetadata?: boolean;
+        uiConfig?: boolean;
+        gqlTada?: boolean;
+        transformIndexHtml?: boolean;
+        translations?: boolean;
+        hmr?: boolean;
+    };
+} & UiConfigPluginOptions &
+    ThemeVariablesPluginOptions
+```
+
+
+## PathAdapter
+
+<GenerationInfo sourceFile="packages/dashboard/vite/types.ts" sourceLine="72" packageName="@vendure/dashboard" since="3.4.0" />
+
+The PathAdapter interface allows customization of how paths are handled
+when compiling the Vendure config and its imports.
+
+It enables support for more complex repository structures, such as
+monorepos, where the Vendure server configuration file may not
+be located in the root directory of the project.
+
+If you get compilation errors like "Error loading Vendure config: Cannot find module",
+you probably need to provide a custom `pathAdapter` to resolve the paths correctly.
+
+This can take some trial-and-error. Try logging values from the functions to figure out
+the exact settings that you need for your repo setup.
+
+*Example*
+
+```ts
+vendureDashboardPlugin({
+    pathAdapter: {
+        getCompiledConfigPath: ({ inputRootDir, outputPath, configFileName }) => {
+            const projectName = inputRootDir.split('/libs/')[1].split('/')[0];
+            const pathAfterProject = inputRootDir.split(`/libs/${projectName}`)[1];
+            const compiledConfigFilePath = `${outputPath}/${projectName}${pathAfterProject}`;
+            return path.join(compiledConfigFilePath, configFileName);
+        },
+        transformTsConfigPathMappings: ({ phase, patterns }) => {
+            // "loading" phase is when the compiled Vendure code is being loaded by
+            // the plugin, in order to introspect the configuration of your app.
+            if (phase === 'loading') {
+                return patterns.map((p) =>
+                    p.replace('libs/', '').replace(/.ts$/, '.js'),
+                );
+            }
+            return patterns;
+        },
+    },
+    // ...
+}),
+```
+
+```ts title="Signature"
+interface PathAdapter {
+    getCompiledConfigPath?: GetCompiledConfigPathFn;
+    transformTsConfigPathMappings?: TransformTsConfigPathMappingsFn;
+}
+```
+
+<div className="members-wrapper">
+
+### getCompiledConfigPath
+
+<MemberInfo kind="property" type={`GetCompiledConfigPathFn`}   />
+
+A function to determine the path to the compiled Vendure config file.
+### transformTsConfigPathMappings
+
+<MemberInfo kind="property" type={`TransformTsConfigPathMappingsFn`}   />
+
+
+
+
+</div>
+
+
+## ApiConfig
+
+<GenerationInfo sourceFile="packages/dashboard/vite/vite-plugin-ui-config.ts" sourceLine="19" packageName="@vendure/dashboard" since="3.4.0" />
+
+Options used by the <a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#venduredashboardplugin'>vendureDashboardPlugin</a> to configure how the Dashboard
+connects to the Vendure Admin API
+
+```ts title="Signature"
+interface ApiConfig {
+    host?: string | 'auto';
+    port?: number | 'auto';
+    adminApiPath?: string;
+    tokenMethod?: 'cookie' | 'bearer';
+    authTokenHeaderKey?: string;
+    channelTokenKey?: string;
+}
+```
+
+<div className="members-wrapper">
+
+### host
+
+<MemberInfo kind="property" type={`string | 'auto'`} default={`'auto'`}   />
+
+The hostname of the Vendure server which the admin UI will be making API calls
+to. If set to "auto", the Admin UI app will determine the hostname from the
+current location (i.e. `window.location.hostname`).
+### port
+
+<MemberInfo kind="property" type={`number | 'auto'`} default={`'auto'`}   />
+
+The port of the Vendure server which the admin UI will be making API calls
+to. If set to "auto", the Admin UI app will determine the port from the
+current location (i.e. `window.location.port`).
+### adminApiPath
+
+<MemberInfo kind="property" type={`string`} default={`'admin-api'`}   />
+
+The path to the GraphQL Admin API.
+### tokenMethod
+
+<MemberInfo kind="property" type={`'cookie' | 'bearer'`} default={`'cookie'`}   />
+
+Whether to use cookies or bearer tokens to track sessions.
+Should match the setting of in the server's `tokenMethod` config
+option.
+### authTokenHeaderKey
+
+<MemberInfo kind="property" type={`string`} default={`'vendure-auth-token'`}   />
+
+The header used when using the 'bearer' auth method. Should match the
+setting of the server's `authOptions.authTokenHeaderKey` config option.
+### channelTokenKey
+
+<MemberInfo kind="property" type={`string`} default={`'vendure-token'`}   />
+
+The name of the header which contains the channel token. Should match the
+setting of the server's `apiOptions.channelTokenKey` config option.
+
+
+</div>
+
+
+## I18nConfig
+
+<GenerationInfo sourceFile="packages/dashboard/vite/vite-plugin-ui-config.ts" sourceLine="81" packageName="@vendure/dashboard" since="3.4.0" />
+
+Options used by the <a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#venduredashboardplugin'>vendureDashboardPlugin</a> to configure aspects of the
+Dashboard UI behaviour.
+
+```ts title="Signature"
+interface I18nConfig {
+    defaultLanguage?: LanguageCode;
+    defaultLocale?: string;
+    availableLanguages?: LanguageCode[];
+    availableLocales?: string[];
+}
+```
+
+<div className="members-wrapper">
+
+### defaultLanguage
+
+<MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>`} default={`<a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>.en`}   />
+
+The default language for the Admin UI. Must be one of the
+items specified in the `availableLanguages` property.
+### defaultLocale
+
+<MemberInfo kind="property" type={`string`}  since="2.2.0"  />
+
+The default locale for the Admin UI. The locale affects the formatting of
+currencies & dates. Must be one of the items specified
+in the `availableLocales` property.
+
+If not set, the browser default locale will be used.
+### availableLanguages
+
+<MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>[]`}   />
+
+An array of languages for which translations exist for the Admin UI.
+### availableLocales
+
+<MemberInfo kind="property" type={`string[]`}  since="2.2.0"  />
+
+An array of locales to be used on Admin UI.
+
+
+</div>
+
+
+## UiConfigPluginOptions
+
+<GenerationInfo sourceFile="packages/dashboard/vite/vite-plugin-ui-config.ts" sourceLine="124" packageName="@vendure/dashboard" since="3.4.0" />
+
+Options used by the <a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#venduredashboardplugin'>vendureDashboardPlugin</a> to configure aspects of the
+Dashboard UI behaviour.
+
+```ts title="Signature"
+interface UiConfigPluginOptions {
+    api?: ApiConfig;
+    i18n?: I18nConfig;
+}
+```
+
+<div className="members-wrapper">
+
+### api
+
+<MemberInfo kind="property" type={`<a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#apiconfig'>ApiConfig</a>`}   />
+
+Configuration for API connection settings
+### i18n
+
+<MemberInfo kind="property" type={`<a href='/reference/dashboard/vite-plugin/vendure-dashboard-plugin#i18nconfig'>I18nConfig</a>`}   />
+
+Configuration for internationalization settings
+
+
+</div>

+ 1 - 1
packages/dashboard/.storybook/main.ts

@@ -55,7 +55,7 @@ const config: StorybookConfig = {
                     },
                     gqlOutputPath: resolve(__dirname, '../src/lib/graphql/'),
                     tempCompilationDir: resolve(__dirname, '../.temp'),
-                    disableTansStackRouterPlugin: true,
+                    disablePlugins: { tanstackRouter: true },
                 }),
             ],
         };

+ 39 - 0
packages/dashboard/vite/types.ts

@@ -29,6 +29,45 @@ export type TransformTsConfigPathMappingsFn = (params: {
  * @description
  * The PathAdapter interface allows customization of how paths are handled
  * when compiling the Vendure config and its imports.
+ *
+ * It enables support for more complex repository structures, such as
+ * monorepos, where the Vendure server configuration file may not
+ * be located in the root directory of the project.
+ *
+ * If you get compilation errors like "Error loading Vendure config: Cannot find module",
+ * you probably need to provide a custom `pathAdapter` to resolve the paths correctly.
+ *
+ * This can take some trial-and-error. Try logging values from the functions to figure out
+ * the exact settings that you need for your repo setup.
+ *
+ * @example
+ * ```ts
+ * vendureDashboardPlugin({
+ *     pathAdapter: {
+ *         getCompiledConfigPath: ({ inputRootDir, outputPath, configFileName }) => {
+ *             const projectName = inputRootDir.split('/libs/')[1].split('/')[0];
+ *             const pathAfterProject = inputRootDir.split(`/libs/${projectName}`)[1];
+ *             const compiledConfigFilePath = `${outputPath}/${projectName}${pathAfterProject}`;
+ *             return path.join(compiledConfigFilePath, configFileName);
+ *         },
+ *         transformTsConfigPathMappings: ({ phase, patterns }) => {
+ *             // "loading" phase is when the compiled Vendure code is being loaded by
+ *             // the plugin, in order to introspect the configuration of your app.
+ *             if (phase === 'loading') {
+ *                 return patterns.map((p) =>
+ *                     p.replace('libs/', '').replace(/.ts$/, '.js'),
+ *                 );
+ *             }
+ *             return patterns;
+ *         },
+ *     },
+ *     // ...
+ * }),
+ * ```
+ *
+ * @docsCategory vite-plugin
+ * @docsPage vendureDashboardPlugin
+ * @since 3.4.0
  */
 export interface PathAdapter {
     /**

+ 27 - 0
packages/dashboard/vite/vite-plugin-ui-config.ts

@@ -7,6 +7,15 @@ import { ConfigLoaderApi, getConfigLoaderApi } from './vite-plugin-config-loader
 const virtualModuleId = 'virtual:vendure-ui-config';
 const resolvedVirtualModuleId = `\0${virtualModuleId}`;
 
+/**
+ * @description
+ * Options used by the {@link vendureDashboardPlugin} to configure how the Dashboard
+ * connects to the Vendure Admin API
+ *
+ * @docsCategory vite-plugin
+ * @docsPage vendureDashboardPlugin
+ * @since 3.4.0
+ */
 export interface ApiConfig {
     /**
      * @description
@@ -60,6 +69,15 @@ export interface ApiConfig {
     channelTokenKey?: string;
 }
 
+/**
+ * @description
+ * Options used by the {@link vendureDashboardPlugin} to configure aspects of the
+ * Dashboard UI behaviour.
+ *
+ * @docsCategory vite-plugin
+ * @docsPage vendureDashboardPlugin
+ * @since 3.4.0
+ */
 export interface I18nConfig {
     /**
      * @description
@@ -94,6 +112,15 @@ export interface I18nConfig {
     availableLocales?: string[];
 }
 
+/**
+ * @description
+ * Options used by the {@link vendureDashboardPlugin} to configure aspects of the
+ * Dashboard UI behaviour.
+ *
+ * @docsCategory vite-plugin
+ * @docsPage vendureDashboardPlugin
+ * @since 3.4.0
+ */
 export interface UiConfigPluginOptions {
     /**
      * @description

+ 18 - 2
packages/dashboard/vite/vite-plugin-vendure-dashboard.ts

@@ -22,6 +22,11 @@ import { uiConfigPlugin, UiConfigPluginOptions } from './vite-plugin-ui-config.j
 /**
  * @description
  * Options for the {@link vendureDashboardPlugin} Vite plugin.
+ *
+ * @docsCategory vite-plugin
+ * @docsPage vendureDashboardPlugin
+ * @since 3.4.0
+ * @docsWeight 1
  */
 export type VitePluginVendureDashboardOptions = {
     /**
@@ -81,7 +86,6 @@ export type VitePluginVendureDashboardOptions = {
      */
     gqlOutputPath?: string;
     tempCompilationDir?: string;
-    disableTansStackRouterPlugin?: boolean;
     /**
      * @description
      * Allows you to customize the location of node_modules & glob patterns used to scan for potential
@@ -134,6 +138,19 @@ type PluginMapEntry = {
     plugin: () => PluginOption | PluginOption[] | false | '';
 };
 
+/**
+ * @description
+ * This is the Vite plugin which powers the Vendure Dashboard, including:
+ *
+ * - Configuring routing, styling and React support
+ * - Analyzing your VendureConfig file and introspecting your schema
+ * - Loading your custom Dashboard extensions
+ *
+ * @docsCategory vite-plugin
+ * @docsPage vendureDashboardPlugin
+ * @since 3.4.0
+ * @docsWeight 0
+ */
 export function vendureDashboardPlugin(options: VitePluginVendureDashboardOptions): PluginOption[] {
     const tempDir = options.tempCompilationDir ?? path.join(import.meta.dirname, './.vendure-dashboard-temp');
     const normalizedVendureConfigPath = getNormalizedVendureConfigPath(options.vendureConfigPath);
@@ -149,7 +166,6 @@ export function vendureDashboardPlugin(options: VitePluginVendureDashboardOption
         {
             key: 'tanstackRouter',
             plugin: () =>
-                !options.disableTansStackRouterPlugin &&
                 tanstackRouter({
                     autoCodeSplitting: true,
                     routeFileIgnorePattern: '.graphql.ts|components|hooks|utils',

+ 1 - 1
scripts/docs/generate-typescript-docs.ts

@@ -75,7 +75,7 @@ const sections: DocsSectionConfig[] = [
         outputPath: 'admin-ui-api',
     },
     {
-        sourceDirs: ['packages/dashboard/src/'],
+        sourceDirs: ['packages/dashboard/src/', 'packages/dashboard/vite/'],
         outputPath: 'dashboard',
     },
 ];