vite-plugin-vendure-dashboard.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import { lingui } from '@lingui/vite-plugin';
  2. import tailwindcss from '@tailwindcss/vite';
  3. import { tanstackRouter } from '@tanstack/router-plugin/vite';
  4. import react from '@vitejs/plugin-react-swc';
  5. import path from 'path';
  6. import { PluginOption } from 'vite';
  7. import { PathAdapter } from './types.js';
  8. import { PackageScannerConfig } from './utils/compiler.js';
  9. import { adminApiSchemaPlugin } from './vite-plugin-admin-api-schema.js';
  10. import { configLoaderPlugin } from './vite-plugin-config-loader.js';
  11. import { viteConfigPlugin } from './vite-plugin-config.js';
  12. import { dashboardMetadataPlugin } from './vite-plugin-dashboard-metadata.js';
  13. import { gqlTadaPlugin } from './vite-plugin-gql-tada.js';
  14. import { hmrPlugin } from './vite-plugin-hmr.js';
  15. import { dashboardTailwindSourcePlugin } from './vite-plugin-tailwind-source.js';
  16. import { themeVariablesPlugin, ThemeVariablesPluginOptions } from './vite-plugin-theme.js';
  17. import { transformIndexHtmlPlugin } from './vite-plugin-transform-index.js';
  18. import { translationsPlugin } from './vite-plugin-translations.js';
  19. import { uiConfigPlugin, UiConfigPluginOptions } from './vite-plugin-ui-config.js';
  20. /**
  21. * @description
  22. * Options for the {@link vendureDashboardPlugin} Vite plugin.
  23. *
  24. * @docsCategory vite-plugin
  25. * @docsPage vendureDashboardPlugin
  26. * @since 3.4.0
  27. * @docsWeight 1
  28. */
  29. export type VitePluginVendureDashboardOptions = {
  30. /**
  31. * @description
  32. * The path to the Vendure server configuration file.
  33. */
  34. vendureConfigPath: string | URL;
  35. /**
  36. * @description
  37. * The {@link PathAdapter} allows you to customize the resolution of paths
  38. * in the compiled Vendure source code which is used as part of the
  39. * introspection step of building the dashboard.
  40. *
  41. * It enables support for more complex repository structures, such as
  42. * monorepos, where the Vendure server configuration file may not
  43. * be located in the root directory of the project.
  44. *
  45. * If you get compilation errors like "Error loading Vendure config: Cannot find module",
  46. * you probably need to provide a custom `pathAdapter` to resolve the paths correctly.
  47. *
  48. * @example
  49. * ```ts
  50. * vendureDashboardPlugin({
  51. * tempCompilationDir: join(__dirname, './__vendure-dashboard-temp'),
  52. * pathAdapter: {
  53. * getCompiledConfigPath: ({ inputRootDir, outputPath, configFileName }) => {
  54. * const projectName = inputRootDir.split('/libs/')[1].split('/')[0];
  55. * const pathAfterProject = inputRootDir.split(`/libs/${projectName}`)[1];
  56. * const compiledConfigFilePath = `${outputPath}/${projectName}${pathAfterProject}`;
  57. * return path.join(compiledConfigFilePath, configFileName);
  58. * },
  59. * transformTsConfigPathMappings: ({ phase, patterns }) => {
  60. * // "loading" phase is when the compiled Vendure code is being loaded by
  61. * // the plugin, in order to introspect the configuration of your app.
  62. * if (phase === 'loading') {
  63. * return patterns.map((p) =>
  64. * p.replace('libs/', '').replace(/.ts$/, '.js'),
  65. * );
  66. * }
  67. * return patterns;
  68. * },
  69. * },
  70. * // ...
  71. * }),
  72. * ```
  73. */
  74. pathAdapter?: PathAdapter;
  75. /**
  76. * @description
  77. * The name of the exported variable from the Vendure server configuration file, e.g. `config`.
  78. * This is only required if the plugin is unable to auto-detect the name of the exported variable.
  79. */
  80. vendureConfigExport?: string;
  81. /**
  82. * @description
  83. * The path to the directory where the generated GraphQL Tada files will be output.
  84. */
  85. gqlOutputPath?: string;
  86. tempCompilationDir?: string;
  87. /**
  88. * @description
  89. * Allows you to customize the location of node_modules & glob patterns used to scan for potential
  90. * Vendure plugins installed as npm packages. If not provided, the compiler will attempt to guess
  91. * the location based on the location of the `@vendure/core` package.
  92. */
  93. pluginPackageScanner?: PackageScannerConfig;
  94. /**
  95. * @description
  96. * Allows you to specify the module system to use when compiling and loading your Vendure config.
  97. * By default, the compiler will use CommonJS, but you can set it to `esm` if you are using
  98. * ES Modules in your Vendure project.
  99. *
  100. * **Status** Developer preview. If you are using ESM please try this out and provide us with feedback!
  101. *
  102. * @since 3.5.1
  103. * @default 'commonjs'
  104. */
  105. module?: 'commonjs' | 'esm';
  106. /**
  107. * @description
  108. * Allows you to selectively disable individual plugins.
  109. * @example
  110. * ```ts
  111. * vendureDashboardPlugin({
  112. * vendureConfigPath: './config.ts',
  113. * disablePlugins: {
  114. * react: true,
  115. * lingui: true,
  116. * }
  117. * })
  118. * ```
  119. */
  120. disablePlugins?: {
  121. tanstackRouter?: boolean;
  122. react?: boolean;
  123. lingui?: boolean;
  124. themeVariables?: boolean;
  125. tailwindSource?: boolean;
  126. tailwindcss?: boolean;
  127. configLoader?: boolean;
  128. viteConfig?: boolean;
  129. adminApiSchema?: boolean;
  130. dashboardMetadata?: boolean;
  131. uiConfig?: boolean;
  132. gqlTada?: boolean;
  133. transformIndexHtml?: boolean;
  134. translations?: boolean;
  135. hmr?: boolean;
  136. };
  137. } & UiConfigPluginOptions &
  138. ThemeVariablesPluginOptions;
  139. /**
  140. * @description
  141. * This is a Vite plugin which configures a set of plugins required to build the Vendure Dashboard.
  142. */
  143. type PluginKey = keyof NonNullable<VitePluginVendureDashboardOptions['disablePlugins']>;
  144. type PluginMapEntry = {
  145. key: PluginKey;
  146. plugin: () => PluginOption | PluginOption[] | false | '';
  147. };
  148. /**
  149. * @description
  150. * This is the Vite plugin which powers the Vendure Dashboard, including:
  151. *
  152. * - Configuring routing, styling and React support
  153. * - Analyzing your VendureConfig file and introspecting your schema
  154. * - Loading your custom Dashboard extensions
  155. *
  156. * @docsCategory vite-plugin
  157. * @docsPage vendureDashboardPlugin
  158. * @since 3.4.0
  159. * @docsWeight 0
  160. */
  161. export function vendureDashboardPlugin(options: VitePluginVendureDashboardOptions): PluginOption[] {
  162. const tempDir = options.tempCompilationDir ?? path.join(import.meta.dirname, './.vendure-dashboard-temp');
  163. const normalizedVendureConfigPath = getNormalizedVendureConfigPath(options.vendureConfigPath);
  164. const packageRoot = getDashboardPackageRoot();
  165. const linguiConfigPath = path.join(packageRoot, 'lingui.config.js');
  166. const disabled = options.disablePlugins ?? {};
  167. if (process.env.IS_LOCAL_DEV !== 'true') {
  168. process.env.LINGUI_CONFIG = linguiConfigPath;
  169. }
  170. const pluginMap: PluginMapEntry[] = [
  171. {
  172. key: 'tanstackRouter',
  173. plugin: () =>
  174. tanstackRouter({
  175. autoCodeSplitting: true,
  176. routeFileIgnorePattern: '.graphql.ts|components|hooks|utils',
  177. routesDirectory: path.join(packageRoot, 'src/app/routes'),
  178. generatedRouteTree: path.join(packageRoot, 'src/app/routeTree.gen.ts'),
  179. }),
  180. },
  181. {
  182. key: 'react',
  183. plugin: () =>
  184. react({
  185. plugins: [['@lingui/swc-plugin', {}]],
  186. }),
  187. },
  188. {
  189. key: 'lingui',
  190. plugin: () => lingui({}),
  191. },
  192. {
  193. key: 'themeVariables',
  194. plugin: () => themeVariablesPlugin({ theme: options.theme }),
  195. },
  196. {
  197. key: 'tailwindSource',
  198. plugin: () => dashboardTailwindSourcePlugin(),
  199. },
  200. {
  201. key: 'tailwindcss',
  202. plugin: () => tailwindcss(),
  203. },
  204. {
  205. key: 'configLoader',
  206. plugin: () =>
  207. configLoaderPlugin({
  208. vendureConfigPath: normalizedVendureConfigPath,
  209. outputPath: tempDir,
  210. pathAdapter: options.pathAdapter,
  211. pluginPackageScanner: options.pluginPackageScanner,
  212. module: options.module,
  213. }),
  214. },
  215. {
  216. key: 'viteConfig',
  217. plugin: () => viteConfigPlugin({ packageRoot }),
  218. },
  219. {
  220. key: 'adminApiSchema',
  221. plugin: () => adminApiSchemaPlugin(),
  222. },
  223. {
  224. key: 'dashboardMetadata',
  225. plugin: () => dashboardMetadataPlugin(),
  226. },
  227. {
  228. key: 'uiConfig',
  229. plugin: () => uiConfigPlugin(options),
  230. },
  231. {
  232. key: 'gqlTada',
  233. plugin: () =>
  234. options.gqlOutputPath &&
  235. gqlTadaPlugin({ gqlTadaOutputPath: options.gqlOutputPath, tempDir, packageRoot }),
  236. },
  237. {
  238. key: 'transformIndexHtml',
  239. plugin: () => transformIndexHtmlPlugin(),
  240. },
  241. {
  242. key: 'translations',
  243. plugin: () =>
  244. translationsPlugin({
  245. packageRoot,
  246. }),
  247. },
  248. {
  249. key: 'hmr',
  250. plugin: () => hmrPlugin(),
  251. },
  252. ];
  253. const plugins: PluginOption[] = [];
  254. for (const entry of pluginMap) {
  255. if (!disabled[entry.key]) {
  256. const plugin = entry.plugin();
  257. if (plugin) {
  258. if (Array.isArray(plugin)) {
  259. plugins.push(...plugin);
  260. } else {
  261. plugins.push(plugin);
  262. }
  263. }
  264. }
  265. }
  266. return plugins;
  267. }
  268. /**
  269. * @description
  270. * Returns the path to the root of the `@vendure/dashboard` package.
  271. */
  272. function getDashboardPackageRoot(): string {
  273. const fileUrl = import.meta.resolve('@vendure/dashboard');
  274. const packagePath = fileUrl.startsWith('file:') ? new URL(fileUrl).pathname : fileUrl;
  275. return fixWindowsPath(path.join(packagePath, '../../../'));
  276. }
  277. /**
  278. * Get the normalized path to the Vendure config file given either a string or URL.
  279. */
  280. export function getNormalizedVendureConfigPath(vendureConfigPath: string | URL): string {
  281. const stringPath = typeof vendureConfigPath === 'string' ? vendureConfigPath : vendureConfigPath.href;
  282. if (stringPath.startsWith('file:')) {
  283. return fixWindowsPath(new URL(stringPath).pathname);
  284. }
  285. return fixWindowsPath(stringPath);
  286. }
  287. function fixWindowsPath(filePath: string): string {
  288. // Fix Windows paths that might start with a leading slash
  289. if (process.platform === 'win32') {
  290. // Remove leading slash before drive letter on Windows
  291. if (/^[/\\][A-Za-z]:/.test(filePath)) {
  292. return filePath.substring(1);
  293. }
  294. }
  295. return filePath;
  296. }