@nx/vite 19.3.0 → 19.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -4
- package/plugins/nx-tsconfig-paths.plugin.js +3 -3
- package/plugins/nx-tsconfig-paths.plugin.js.map +1 -1
- package/src/generators/init/init.js +1 -1
- package/src/generators/init/init.js.map +1 -1
- package/src/generators/setup-paths-plugin/setup-paths-plugin.js +3 -0
- package/src/generators/setup-paths-plugin/setup-paths-plugin.js.map +1 -1
- package/src/plugins/plugin.js +18 -8
- package/src/plugins/plugin.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nx/vite",
|
|
3
|
-
"version": "19.3.
|
|
3
|
+
"version": "19.3.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "The Nx Plugin for building and testing applications using Vite",
|
|
6
6
|
"repository": {
|
|
@@ -30,13 +30,13 @@
|
|
|
30
30
|
"migrations": "./migrations.json"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@nx/devkit": "19.3.
|
|
33
|
+
"@nx/devkit": "19.3.2",
|
|
34
34
|
"@phenomnomnominal/tsquery": "~5.0.1",
|
|
35
35
|
"@swc/helpers": "~0.5.0",
|
|
36
36
|
"enquirer": "~2.3.6",
|
|
37
|
-
"@nx/js": "19.3.
|
|
37
|
+
"@nx/js": "19.3.2",
|
|
38
38
|
"tsconfig-paths": "^4.1.2",
|
|
39
|
-
"@nrwl/vite": "19.3.
|
|
39
|
+
"@nrwl/vite": "19.3.2"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"vite": "^5.0.0",
|
|
@@ -51,7 +51,7 @@ function nxViteTsPaths(options = {}) {
|
|
|
51
51
|
throw new Error((0, _devkit.stripIndents)`Unable to find a tsconfig in the workspace!
|
|
52
52
|
There should at least be a tsconfig.base.json or tsconfig.json in the root of the workspace ${_devkit.workspaceRoot}`);
|
|
53
53
|
}
|
|
54
|
-
if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION) {
|
|
54
|
+
if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION && config.mode !== 'test') {
|
|
55
55
|
const projectGraph = await (0, _devkit.createProjectGraphAsync)({
|
|
56
56
|
exitOnError: false,
|
|
57
57
|
resetDaemonClient: true
|
|
@@ -61,7 +61,7 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
|
|
|
61
61
|
process.env.NX_TASK_TARGET_TARGET === 'serve' ? 'build' : process.env.NX_TASK_TARGET_TARGET, process.env.NX_TASK_TARGET_CONFIGURATION);
|
|
62
62
|
// This tsconfig is used via the Vite ts paths plugin.
|
|
63
63
|
// It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).
|
|
64
|
-
foundTsConfigPath = (0, _buildablelibsutils.createTmpTsConfig)(foundTsConfigPath, _devkit.workspaceRoot, (0, _nodepath.relative)(_devkit.workspaceRoot, projectRoot), dependencies);
|
|
64
|
+
foundTsConfigPath = (0, _buildablelibsutils.createTmpTsConfig)(foundTsConfigPath, _devkit.workspaceRoot, (0, _nodepath.relative)(_devkit.workspaceRoot, projectRoot), dependencies, true);
|
|
65
65
|
if (config.command === 'serve') {
|
|
66
66
|
const buildableLibraryDependencies = dependencies.filter((dep)=>dep.node.type === 'lib').map((dep)=>dep.node.name).join(',');
|
|
67
67
|
const buildCommand = `npx nx run-many --target=${process.env.NX_TASK_TARGET_TARGET} --projects=${buildableLibraryDependencies}`;
|
|
@@ -73,7 +73,7 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
|
|
|
73
73
|
const parsed = (0, _tsconfigpaths.loadConfig)(foundTsConfigPath);
|
|
74
74
|
logIt('first parsed tsconfig: ', parsed);
|
|
75
75
|
if (parsed.resultType === 'failed') {
|
|
76
|
-
throw new Error(`Failed loading
|
|
76
|
+
throw new Error(`Failed loading tsconfig at ${foundTsConfigPath}`);
|
|
77
77
|
}
|
|
78
78
|
tsConfigPathsEsm = parsed;
|
|
79
79
|
matchTsPathEsm = (0, _tsconfigpaths.createMatchPath)(parsed.absoluteBaseUrl, parsed.paths, options.mainFields);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../packages/vite/plugins/nx-tsconfig-paths.plugin.ts"],"sourcesContent":["import {\n createProjectGraphAsync,\n joinPathFragments,\n stripIndents,\n workspaceRoot,\n} from '@nx/devkit';\nimport { copyFileSync, existsSync } from 'node:fs';\nimport { relative, join, resolve } from 'node:path';\nimport {\n loadConfig,\n createMatchPath,\n MatchPath,\n ConfigLoaderSuccessResult,\n} from 'tsconfig-paths';\nimport {\n calculateProjectBuildableDependencies,\n createTmpTsConfig,\n} from '@nx/js/src/utils/buildable-libs-utils';\nimport { Plugin } from 'vite';\nimport { nxViteBuildCoordinationPlugin } from './nx-vite-build-coordination.plugin';\n\nexport interface nxViteTsPathsOptions {\n /**\n * Enable debug logging\n * @default false\n **/\n debug?: boolean;\n /**\n * export fields in package.json to use for resolving\n * @default [['exports', '.', 'import'], 'module', 'main']\n *\n * fallback resolution will use ['main', 'module']\n **/\n mainFields?: (string | string[])[];\n /**\n * extensions to check when resolving files when package.json resolution fails\n * @default ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs', '.cjs']\n **/\n extensions?: string[];\n /**\n * Inform Nx whether to use the raw source or to use the built output for buildable dependencies.\n * Set to `false` to use incremental builds.\n * @default true\n */\n buildLibsFromSource?: boolean;\n}\n\nexport function nxViteTsPaths(options: nxViteTsPathsOptions = {}) {\n let matchTsPathEsm: MatchPath;\n let matchTsPathFallback: MatchPath | undefined;\n let tsConfigPathsEsm: ConfigLoaderSuccessResult;\n let tsConfigPathsFallback: ConfigLoaderSuccessResult;\n\n options.extensions ??= [\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.mjs',\n '.cjs',\n ];\n options.mainFields ??= [['exports', '.', 'import'], 'module', 'main'];\n options.buildLibsFromSource ??= true;\n let projectRoot = '';\n\n return {\n name: 'nx-vite-ts-paths',\n async configResolved(config: any) {\n projectRoot = config.root;\n const projectRootFromWorkspaceRoot = relative(workspaceRoot, projectRoot);\n let foundTsConfigPath = getTsConfig(\n join(\n workspaceRoot,\n 'tmp',\n projectRootFromWorkspaceRoot,\n process.env.NX_TASK_TARGET_TARGET ?? 'build',\n 'tsconfig.generated.json'\n )\n );\n if (!foundTsConfigPath) {\n throw new Error(stripIndents`Unable to find a tsconfig in the workspace! \nThere should at least be a tsconfig.base.json or tsconfig.json in the root of the workspace ${workspaceRoot}`);\n }\n\n if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION) {\n const projectGraph = await createProjectGraphAsync({\n exitOnError: false,\n resetDaemonClient: true,\n });\n const { dependencies } = calculateProjectBuildableDependencies(\n undefined,\n projectGraph,\n workspaceRoot,\n process.env.NX_TASK_TARGET_PROJECT,\n // When using incremental building and the serve target is called\n // we need to get the deps for the 'build' target instead.\n process.env.NX_TASK_TARGET_TARGET === 'serve'\n ? 'build'\n : process.env.NX_TASK_TARGET_TARGET,\n process.env.NX_TASK_TARGET_CONFIGURATION\n );\n // This tsconfig is used via the Vite ts paths plugin.\n // It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).\n foundTsConfigPath = createTmpTsConfig(\n foundTsConfigPath,\n workspaceRoot,\n relative(workspaceRoot, projectRoot),\n dependencies\n );\n\n if (config.command === 'serve') {\n const buildableLibraryDependencies = dependencies\n .filter((dep) => dep.node.type === 'lib')\n .map((dep) => dep.node.name)\n .join(',');\n const buildCommand = `npx nx run-many --target=${process.env.NX_TASK_TARGET_TARGET} --projects=${buildableLibraryDependencies}`;\n config.plugins.push(nxViteBuildCoordinationPlugin({ buildCommand }));\n }\n }\n\n const parsed = loadConfig(foundTsConfigPath);\n\n logIt('first parsed tsconfig: ', parsed);\n if (parsed.resultType === 'failed') {\n throw new Error(`Failed loading tsonfig at ${foundTsConfigPath}`);\n }\n tsConfigPathsEsm = parsed;\n\n matchTsPathEsm = createMatchPath(\n parsed.absoluteBaseUrl,\n parsed.paths,\n options.mainFields\n );\n\n const rootLevelTsConfig = getTsConfig(\n join(workspaceRoot, 'tsconfig.base.json')\n );\n const rootLevelParsed = loadConfig(rootLevelTsConfig);\n logIt('fallback parsed tsconfig: ', rootLevelParsed);\n if (rootLevelParsed.resultType === 'success') {\n tsConfigPathsFallback = rootLevelParsed;\n matchTsPathFallback = createMatchPath(\n rootLevelParsed.absoluteBaseUrl,\n rootLevelParsed.paths,\n ['main', 'module']\n );\n }\n },\n resolveId(importPath: string) {\n let resolvedFile: string;\n try {\n resolvedFile = matchTsPathEsm(importPath);\n } catch (e) {\n logIt('Using fallback path matching.');\n resolvedFile = matchTsPathFallback?.(importPath);\n }\n\n if (!resolvedFile) {\n if (tsConfigPathsEsm || tsConfigPathsFallback) {\n logIt(\n `Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`\n );\n resolvedFile =\n loadFileFromPaths(tsConfigPathsEsm, importPath) ||\n loadFileFromPaths(tsConfigPathsFallback, importPath);\n } else {\n logIt(`Unable to resolve ${importPath} with tsconfig paths`);\n }\n }\n\n logIt(`Resolved ${importPath} to ${resolvedFile}`);\n // Returning null defers to other resolveId functions and eventually the default resolution behavior\n // https://rollupjs.org/plugin-development/#resolveid\n return resolvedFile || null;\n },\n async writeBundle(options) {\n const outDir = options.dir || 'dist';\n const src = resolve(projectRoot, 'package.json');\n if (existsSync(src)) {\n const dest = join(outDir, 'package.json');\n\n try {\n copyFileSync(src, dest);\n } catch (err) {\n console.error('Error copying package.json:', err);\n }\n }\n },\n } as Plugin;\n\n function getTsConfig(preferredTsConfigPath: string): string {\n return [\n resolve(preferredTsConfigPath),\n resolve(join(workspaceRoot, 'tsconfig.base.json')),\n resolve(join(workspaceRoot, 'tsconfig.json')),\n ].find((tsPath) => {\n if (existsSync(tsPath)) {\n logIt('Found tsconfig at', tsPath);\n return tsPath;\n }\n });\n }\n\n function logIt(...msg: any[]) {\n if (process.env.NX_VERBOSE_LOGGING === 'true' || options?.debug) {\n console.debug('\\n[Nx Vite TsPaths]', ...msg);\n }\n }\n\n function loadFileFromPaths(\n tsconfig: ConfigLoaderSuccessResult,\n importPath: string\n ) {\n logIt(\n `Trying to resolve file from config in ${tsconfig.configFileAbsolutePath}`\n );\n let resolvedFile: string;\n for (const alias in tsconfig.paths) {\n const paths = tsconfig.paths[alias];\n\n const normalizedImport = alias.replace(/\\/\\*$/, '');\n\n if (importPath.startsWith(normalizedImport)) {\n const joinedPath = joinPathFragments(\n tsconfig.absoluteBaseUrl,\n paths[0].replace(/\\/\\*$/, '')\n );\n\n resolvedFile = findFile(\n importPath.replace(normalizedImport, joinedPath)\n );\n }\n }\n\n return resolvedFile;\n }\n\n function findFile(path: string): string {\n for (const ext of options.extensions) {\n const resolvedPath = resolve(path + ext);\n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n\n const resolvedIndexPath = resolve(path, `index${ext}`);\n if (existsSync(resolvedIndexPath)) {\n return resolvedIndexPath;\n }\n }\n }\n}\n"],"names":["nxViteTsPaths","options","matchTsPathEsm","matchTsPathFallback","tsConfigPathsEsm","tsConfigPathsFallback","extensions","mainFields","buildLibsFromSource","projectRoot","name","configResolved","config","root","projectRootFromWorkspaceRoot","relative","workspaceRoot","process","foundTsConfigPath","getTsConfig","join","env","NX_TASK_TARGET_TARGET","Error","stripIndents","global","NX_GRAPH_CREATION","projectGraph","createProjectGraphAsync","exitOnError","resetDaemonClient","dependencies","calculateProjectBuildableDependencies","undefined","NX_TASK_TARGET_PROJECT","NX_TASK_TARGET_CONFIGURATION","createTmpTsConfig","command","buildableLibraryDependencies","filter","dep","node","type","map","buildCommand","plugins","push","nxViteBuildCoordinationPlugin","parsed","loadConfig","logIt","resultType","createMatchPath","absoluteBaseUrl","paths","rootLevelTsConfig","rootLevelParsed","resolveId","importPath","resolvedFile","e","loadFileFromPaths","writeBundle","outDir","dir","src","resolve","existsSync","dest","copyFileSync","err","console","error","preferredTsConfigPath","find","tsPath","msg","NX_VERBOSE_LOGGING","debug","tsconfig","configFileAbsolutePath","alias","normalizedImport","replace","startsWith","joinedPath","joinPathFragments","findFile","path","ext","resolvedPath","resolvedIndexPath"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BA+CgBA;;;eAAAA;;;wBA1CT;wBACkC;0BACD;+BAMjC;oCAIA;+CAEuC;AA4BvC,SAASA,cAAcC,UAAgC,CAAC,CAAC;QAM9DA,UASAA,WACAA;IAfA,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;;IAEJJ,gBAAAA,WAAAA,SAAQK,oCAARL,SAAQK,aAAe;QACrB;QACA;QACA;QACA;QACA;QACA;QACA;KACD;;IACDL,gBAAAA,YAAAA,SAAQM,oCAARN,UAAQM,aAAe;QAAC;YAAC;YAAW;YAAK;SAAS;QAAE;QAAU;KAAO;;IACrEN,yBAAAA,YAAAA,SAAQO,sDAARP,UAAQO,sBAAwB;IAChC,IAAIC,cAAc;IAElB,OAAO;QACLC,MAAM;QACN,MAAMC,gBAAeC,MAAW;YAC9BH,cAAcG,OAAOC,IAAI;YACzB,MAAMC,+BAA+BC,IAAAA,kBAAQ,EAACC,qBAAa,EAAEP;gBAMzDQ;YALJ,IAAIC,oBAAoBC,YACtBC,IAAAA,cAAI,EACFJ,qBAAa,EACb,OACAF,8BACAG,CAAAA,qCAAAA,QAAQI,GAAG,CAACC,qBAAqB,YAAjCL,qCAAqC,SACrC;YAGJ,IAAI,CAACC,mBAAmB;gBACtB,MAAM,IAAIK,MAAMC,IAAAA,oBAAY,CAAA,CAAC;4FACuD,EAAER,qBAAa,CAAC,CAAC;YACvG;YAEA,IAAI,CAACf,QAAQO,mB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EAAEC,IAAI,CAAC;YACrD,IAAItB,IAAAA,kBAAU,EAACwB,oBAAoB;gBACjC,OAAOA;YACT;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../packages/vite/plugins/nx-tsconfig-paths.plugin.ts"],"sourcesContent":["import {\n createProjectGraphAsync,\n joinPathFragments,\n stripIndents,\n workspaceRoot,\n} from '@nx/devkit';\nimport { copyFileSync, existsSync } from 'node:fs';\nimport { relative, join, resolve } from 'node:path';\nimport {\n loadConfig,\n createMatchPath,\n MatchPath,\n ConfigLoaderSuccessResult,\n} from 'tsconfig-paths';\nimport {\n calculateProjectBuildableDependencies,\n createTmpTsConfig,\n} from '@nx/js/src/utils/buildable-libs-utils';\nimport { Plugin } from 'vite';\nimport { nxViteBuildCoordinationPlugin } from './nx-vite-build-coordination.plugin';\n\nexport interface nxViteTsPathsOptions {\n /**\n * Enable debug logging\n * @default false\n **/\n debug?: boolean;\n /**\n * export fields in package.json to use for resolving\n * @default [['exports', '.', 'import'], 'module', 'main']\n *\n * fallback resolution will use ['main', 'module']\n **/\n mainFields?: (string | string[])[];\n /**\n * extensions to check when resolving files when package.json resolution fails\n * @default ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs', '.cjs']\n **/\n extensions?: string[];\n /**\n * Inform Nx whether to use the raw source or to use the built output for buildable dependencies.\n * Set to `false` to use incremental builds.\n * @default true\n */\n buildLibsFromSource?: boolean;\n}\n\nexport function nxViteTsPaths(options: nxViteTsPathsOptions = {}) {\n let matchTsPathEsm: MatchPath;\n let matchTsPathFallback: MatchPath | undefined;\n let tsConfigPathsEsm: ConfigLoaderSuccessResult;\n let tsConfigPathsFallback: ConfigLoaderSuccessResult;\n\n options.extensions ??= [\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.mjs',\n '.cjs',\n ];\n options.mainFields ??= [['exports', '.', 'import'], 'module', 'main'];\n options.buildLibsFromSource ??= true;\n let projectRoot = '';\n\n return {\n name: 'nx-vite-ts-paths',\n async configResolved(config: any) {\n projectRoot = config.root;\n const projectRootFromWorkspaceRoot = relative(workspaceRoot, projectRoot);\n let foundTsConfigPath = getTsConfig(\n join(\n workspaceRoot,\n 'tmp',\n projectRootFromWorkspaceRoot,\n process.env.NX_TASK_TARGET_TARGET ?? 'build',\n 'tsconfig.generated.json'\n )\n );\n if (!foundTsConfigPath) {\n throw new Error(stripIndents`Unable to find a tsconfig in the workspace! \nThere should at least be a tsconfig.base.json or tsconfig.json in the root of the workspace ${workspaceRoot}`);\n }\n\n if (\n !options.buildLibsFromSource &&\n !global.NX_GRAPH_CREATION &&\n config.mode !== 'test'\n ) {\n const projectGraph = await createProjectGraphAsync({\n exitOnError: false,\n resetDaemonClient: true,\n });\n const { dependencies } = calculateProjectBuildableDependencies(\n undefined,\n projectGraph,\n workspaceRoot,\n process.env.NX_TASK_TARGET_PROJECT,\n // When using incremental building and the serve target is called\n // we need to get the deps for the 'build' target instead.\n process.env.NX_TASK_TARGET_TARGET === 'serve'\n ? 'build'\n : process.env.NX_TASK_TARGET_TARGET,\n process.env.NX_TASK_TARGET_CONFIGURATION\n );\n // This tsconfig is used via the Vite ts paths plugin.\n // It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).\n foundTsConfigPath = createTmpTsConfig(\n foundTsConfigPath,\n workspaceRoot,\n relative(workspaceRoot, projectRoot),\n dependencies,\n true\n );\n\n if (config.command === 'serve') {\n const buildableLibraryDependencies = dependencies\n .filter((dep) => dep.node.type === 'lib')\n .map((dep) => dep.node.name)\n .join(',');\n const buildCommand = `npx nx run-many --target=${process.env.NX_TASK_TARGET_TARGET} --projects=${buildableLibraryDependencies}`;\n config.plugins.push(nxViteBuildCoordinationPlugin({ buildCommand }));\n }\n }\n\n const parsed = loadConfig(foundTsConfigPath);\n\n logIt('first parsed tsconfig: ', parsed);\n if (parsed.resultType === 'failed') {\n throw new Error(`Failed loading tsconfig at ${foundTsConfigPath}`);\n }\n tsConfigPathsEsm = parsed;\n\n matchTsPathEsm = createMatchPath(\n parsed.absoluteBaseUrl,\n parsed.paths,\n options.mainFields\n );\n\n const rootLevelTsConfig = getTsConfig(\n join(workspaceRoot, 'tsconfig.base.json')\n );\n const rootLevelParsed = loadConfig(rootLevelTsConfig);\n logIt('fallback parsed tsconfig: ', rootLevelParsed);\n if (rootLevelParsed.resultType === 'success') {\n tsConfigPathsFallback = rootLevelParsed;\n matchTsPathFallback = createMatchPath(\n rootLevelParsed.absoluteBaseUrl,\n rootLevelParsed.paths,\n ['main', 'module']\n );\n }\n },\n resolveId(importPath: string) {\n let resolvedFile: string;\n try {\n resolvedFile = matchTsPathEsm(importPath);\n } catch (e) {\n logIt('Using fallback path matching.');\n resolvedFile = matchTsPathFallback?.(importPath);\n }\n\n if (!resolvedFile) {\n if (tsConfigPathsEsm || tsConfigPathsFallback) {\n logIt(\n `Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`\n );\n resolvedFile =\n loadFileFromPaths(tsConfigPathsEsm, importPath) ||\n loadFileFromPaths(tsConfigPathsFallback, importPath);\n } else {\n logIt(`Unable to resolve ${importPath} with tsconfig paths`);\n }\n }\n\n logIt(`Resolved ${importPath} to ${resolvedFile}`);\n // Returning null defers to other resolveId functions and eventually the default resolution behavior\n // https://rollupjs.org/plugin-development/#resolveid\n return resolvedFile || null;\n },\n async writeBundle(options) {\n const outDir = options.dir || 'dist';\n const src = resolve(projectRoot, 'package.json');\n if (existsSync(src)) {\n const dest = join(outDir, 'package.json');\n\n try {\n copyFileSync(src, dest);\n } catch (err) {\n console.error('Error copying package.json:', err);\n }\n }\n },\n } as Plugin;\n\n function getTsConfig(preferredTsConfigPath: string): string {\n return [\n resolve(preferredTsConfigPath),\n resolve(join(workspaceRoot, 'tsconfig.base.json')),\n resolve(join(workspaceRoot, 'tsconfig.json')),\n ].find((tsPath) => {\n if (existsSync(tsPath)) {\n logIt('Found tsconfig at', tsPath);\n return tsPath;\n }\n });\n }\n\n function logIt(...msg: any[]) {\n if (process.env.NX_VERBOSE_LOGGING === 'true' || options?.debug) {\n console.debug('\\n[Nx Vite TsPaths]', ...msg);\n }\n }\n\n function loadFileFromPaths(\n tsconfig: ConfigLoaderSuccessResult,\n importPath: string\n ) {\n logIt(\n `Trying to resolve file from config in ${tsconfig.configFileAbsolutePath}`\n );\n let resolvedFile: string;\n for (const alias in tsconfig.paths) {\n const paths = tsconfig.paths[alias];\n\n const normalizedImport = alias.replace(/\\/\\*$/, '');\n\n if (importPath.startsWith(normalizedImport)) {\n const joinedPath = joinPathFragments(\n tsconfig.absoluteBaseUrl,\n paths[0].replace(/\\/\\*$/, '')\n );\n\n resolvedFile = findFile(\n importPath.replace(normalizedImport, joinedPath)\n );\n }\n }\n\n return resolvedFile;\n }\n\n function findFile(path: string): string {\n for (const ext of options.extensions) {\n const resolvedPath = resolve(path + ext);\n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n\n const resolvedIndexPath = resolve(path, `index${ext}`);\n if (existsSync(resolvedIndexPath)) {\n return resolvedIndexPath;\n }\n }\n }\n}\n"],"names":["nxViteTsPaths","options","matchTsPathEsm","matchTsPathFallback","tsConfigPathsEsm","tsConfigPathsFallback","extensions","mainFields","buildLibsFromSource","projectRoot","name","configResolved","config","root","projectRootFromWorkspaceRoot","relative","workspaceRoot","process","foundTsConfigPath","getTsConfig","join","env","NX_TASK_TARGET_TARGET","Error","stripIndents","global","NX_GRAPH_CREATION","mode","projectGraph","createProjectGraphAsync","exitOnError","resetDaemonClient","dependencies","calculateProjectBuildableDependencies","undefined","NX_TASK_TARGET_PROJECT","NX_TASK_TARGET_CONFIGURATION","createTmpTsConfig","command","buildableLibraryDependencies","filter","dep","node","type","map","buildCommand","plugins","push","nxViteBuildCoordinationPlugin","parsed","loadConfig","logIt","resultType","createMatchPath","absoluteBaseUrl","paths","rootLevelTsConfig","rootLevelParsed","resolveId","importPath","resolvedFile","e","loadFileFromPaths","writeBundle","outDir","dir","src","resolve","existsSync","dest","copyFileSync","err","console","error","preferredTsConfigPath","find","tsPath","msg","NX_VERBOSE_LOGGING","debug","tsconfig","configFileAbsolutePath","alias","normalizedImport","replace","startsWith","joinedPath","joinPathFragments","findFile","path","ext","resolvedPath","resolvedIndexPath"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BA+CgBA;;;eAAAA;;;wBA1CT;wBACkC;0BACD;+BAMjC;oCAIA;+CAEuC;AA4BvC,SAASA,cAAcC,UAAgC,CAAC,CAAC;QAM9DA,UASAA,WACAA;IAfA,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;;IAEJJ,gBAAAA,WAAAA,SAAQK,oCAARL,SAAQK,aAAe;QACrB;QACA;QACA;QACA;QACA;QACA;QACA;KACD;;IACDL,gBAAAA,YAAAA,SAAQM,oCAARN,UAAQM,aAAe;QAAC;YAAC;YAAW;YAAK;SAAS;QAAE;QAAU;KAAO;;IACrEN,yBAAAA,YAAAA,SAAQO,sDAARP,UAAQO,sBAAwB;IAChC,IAAIC,cAAc;IAElB,OAAO;QACLC,MAAM;QACN,MAAMC,gBAAeC,MAAW;YAC9BH,cAAcG,OAAOC,IAAI;YACzB,MAAMC,+BAA+BC,IAAAA,kBAAQ,EAACC,qBAAa,EAAEP;gBAMzDQ;YALJ,IAAIC,oBAAoBC,YACtBC,IAAAA,cAAI,EACFJ,qBAAa,EACb,OACAF,8BACAG,CAAAA,qCAAAA,QAAQI,GAAG,CAACC,qBAAqB,YAAjCL,qCAAqC,SACrC;YAGJ,IAAI,CAACC,mBAAmB;gBACtB,MAAM,IAAIK,MAAMC,IAAAA,oBAAY,CAAA,CAAC;4FACuD,EAAER,qBAAa,CAAC,CAAC;YACvG;YAEA,IACE,CAACf,QAAQO,mBAAmB,IAC5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ACsB,MAAM,CAAC,KAAK,EAAEC,IAAI,CAAC;YACrD,IAAItB,IAAAA,kBAAU,EAACwB,oBAAoB;gBACjC,OAAOA;YACT;QACF;IACF;AACF"}
|
|
@@ -62,7 +62,7 @@ async function initGeneratorInternal(tree, schema) {
|
|
|
62
62
|
var _addPlugin;
|
|
63
63
|
(_addPlugin = (_schema = schema).addPlugin) != null ? _addPlugin : _schema.addPlugin = addPluginDefault;
|
|
64
64
|
if (schema.addPlugin) {
|
|
65
|
-
await (0, _addplugin.
|
|
65
|
+
await (0, _addplugin.addPlugin)(tree, await (0, _devkit.createProjectGraphAsync)(), '@nx/vite/plugin', _plugin.createNodesV2, {
|
|
66
66
|
buildTargetName: [
|
|
67
67
|
'build',
|
|
68
68
|
'vite:build',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/vite/src/generators/init/init.ts"],"sourcesContent":["import {\n createProjectGraphAsync,\n formatFiles,\n GeneratorCallback,\n readNxJson,\n runTasksInSerial,\n Tree,\n updateNxJson,\n} from '@nx/devkit';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/vite/src/generators/init/init.ts"],"sourcesContent":["import {\n createProjectGraphAsync,\n formatFiles,\n GeneratorCallback,\n readNxJson,\n runTasksInSerial,\n Tree,\n updateNxJson,\n} from '@nx/devkit';\nimport { addPlugin } from '@nx/devkit/src/utils/add-plugin';\n\nimport { setupPathsPlugin } from '../setup-paths-plugin/setup-paths-plugin';\nimport { createNodesV2 } from '../../plugins/plugin';\nimport { InitGeneratorSchema } from './schema';\nimport { checkDependenciesInstalled, moveToDevDependencies } from './lib/utils';\n\nexport function updateNxJsonSettings(tree: Tree) {\n const nxJson = readNxJson(tree);\n\n const productionFileSet = nxJson.namedInputs?.production;\n if (productionFileSet) {\n productionFileSet.push(\n '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)',\n '!{projectRoot}/tsconfig.spec.json'\n );\n\n nxJson.namedInputs.production = Array.from(new Set(productionFileSet));\n }\n\n const hasPlugin = nxJson.plugins?.some((p) =>\n typeof p === 'string'\n ? p === '@nx/vite/plugin'\n : p.plugin === '@nx/vite/plugin'\n );\n\n if (!hasPlugin) {\n nxJson.targetDefaults ??= {};\n nxJson.targetDefaults['@nx/vite:test'] ??= {};\n nxJson.targetDefaults['@nx/vite:test'].cache ??= true;\n nxJson.targetDefaults['@nx/vite:test'].inputs ??= [\n 'default',\n productionFileSet ? '^production' : '^default',\n ];\n }\n\n updateNxJson(tree, nxJson);\n}\n\nexport function initGenerator(tree: Tree, schema: InitGeneratorSchema) {\n return initGeneratorInternal(tree, { addPlugin: false, ...schema });\n}\n\nexport async function initGeneratorInternal(\n tree: Tree,\n schema: InitGeneratorSchema\n) {\n const nxJson = readNxJson(tree);\n const addPluginDefault =\n process.env.NX_ADD_PLUGINS !== 'false' &&\n nxJson.useInferencePlugins !== false;\n schema.addPlugin ??= addPluginDefault;\n\n if (schema.addPlugin) {\n await addPlugin(\n tree,\n await createProjectGraphAsync(),\n '@nx/vite/plugin',\n createNodesV2,\n {\n buildTargetName: ['build', 'vite:build', 'vite-build'],\n testTargetName: ['test', 'vite:test', 'vite-test'],\n serveTargetName: ['serve', 'vite:serve', 'vite-serve'],\n previewTargetName: ['preview', 'vite:preview', 'vite-preview'],\n serveStaticTargetName: [\n 'serve-static',\n 'vite:serve-static',\n 'vite-serve-static',\n ],\n },\n schema.updatePackageScripts\n );\n }\n\n updateNxJsonSettings(tree);\n\n if (schema.setupPathsPlugin) {\n await setupPathsPlugin(tree, { skipFormat: true });\n }\n\n const tasks: GeneratorCallback[] = [];\n if (!schema.skipPackageJson) {\n tasks.push(moveToDevDependencies(tree));\n tasks.push(checkDependenciesInstalled(tree, schema));\n }\n\n if (!schema.skipFormat) {\n await formatFiles(tree);\n }\n\n return runTasksInSerial(...tasks);\n}\n\nexport default initGenerator;\n"],"names":["initGenerator","initGeneratorInternal","updateNxJsonSettings","tree","nxJson","readNxJson","productionFileSet","namedInputs","production","push","Array","from","Set","hasPlugin","plugins","some","p","plugin","targetDefaults","cache","inputs","updateNxJson","schema","addPlugin","addPluginDefault","process","env","NX_ADD_PLUGINS","useInferencePlugins","createProjectGraphAsync","createNodesV2","buildTargetName","testTargetName","serveTargetName","previewTargetName","serveStaticTargetName","updatePackageScripts","setupPathsPlugin","skipFormat","tasks","skipPackageJson","moveToDevDependencies","checkDependenciesInstalled","formatFiles","runTasksInSerial"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAsGA,OAA6B;eAA7B;;IAtDgBA,aAAa;eAAbA;;IAIMC,qBAAqB;eAArBA;;IApCNC,oBAAoB;eAApBA;;;;wBART;2BACmB;kCAEO;wBACH;uBAEoC;AAE3D,SAASA,qBAAqBC,IAAU;QAGnBC,qBAURA;IAZlB,MAAMA,SAASC,IAAAA,kBAAU,EAACF;IAE1B,MAAMG,qBAAoBF,sBAAAA,OAAOG,WAAW,qBAAlBH,oBAAoBI,UAAU;IACxD,IAAIF,mBAAmB;QACrBA,kBAAkBG,IAAI,CACpB,yDACA;QAGFL,OAAOG,WAAW,CAACC,UAAU,GAAGE,MAAMC,IAAI,CAAC,IAAIC,IAAIN;IACrD;IAEA,MAAMO,aAAYT,kBAAAA,OAAOU,OAAO,qBAAdV,gBAAgBW,IAAI,CAAC,CAACC,IACtC,OAAOA,MAAM,WACTA,MAAM,oBACNA,EAAEC,MAAM,KAAK;IAGnB,IAAI,CAACJ,WAAW;YACdT,SACAA,wBAAsB,aACtBA,mCACAA;;QAHAA,oBAAAA,UAAAA,QAAOc,4CAAPd,QAAOc,iBAAmB,CAAC;;QAC3Bd,MAAAA,yBAAAA,OAAOc,cAAc,CAAA,CAAC,cAAA,gBAAgB,gBAAtCd,sBAAqB,CAAC,YAAgB,GAAK,CAAC;;QAC5C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B,EAACvC,MAAMmB;IAC9C;IAEA,IAAI,CAACA,OAAOgB,UAAU,EAAE;QACtB,MAAMK,IAAAA,mBAAW,EAACxC;IACpB;IAEA,OAAOyC,IAAAA,wBAAgB,KAAIL;AAC7B;MAEA,WAAevC"}
|
|
@@ -31,6 +31,9 @@ function ensureImportExists(tree, file) {
|
|
|
31
31
|
let content = tree.read(file, 'utf-8');
|
|
32
32
|
const ast = tsquery.ast(content);
|
|
33
33
|
const allImports = tsquery.query(ast, 'ImportDeclaration');
|
|
34
|
+
if (content.includes('@nx/vite/plugins/nx-tsconfig-paths.plugin')) {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
34
37
|
if (allImports.length) {
|
|
35
38
|
const lastImport = allImports[allImports.length - 1];
|
|
36
39
|
tree.write(file, (0, _devkit.applyChangesToString)(content, [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/vite/src/generators/setup-paths-plugin/setup-paths-plugin.ts"],"sourcesContent":["import {\n applyChangesToString,\n ChangeType,\n formatFiles,\n globAsync,\n Tree,\n} from '@nx/devkit';\nimport type { ArrayLiteralExpression, Node } from 'typescript';\n\nexport async function setupPathsPlugin(\n tree: Tree,\n schema: { skipFormat?: boolean }\n) {\n const files = await globAsync(tree, [\n '**/vite.config.{js,ts,mjs,mts,cjs,cts}',\n ]);\n\n for (const file of files) {\n ensureImportExists(tree, file);\n ensurePluginAdded(tree, file);\n }\n\n if (!schema.skipFormat) {\n await formatFiles(tree);\n }\n}\n\nfunction ensureImportExists(tree, file) {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n let content = tree.read(file, 'utf-8');\n const ast = tsquery.ast(content);\n const allImports = tsquery.query(ast, 'ImportDeclaration');\n if (allImports.length) {\n const lastImport = allImports[allImports.length - 1];\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: lastImport.end + 1,\n text: `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\\n`,\n },\n ])\n );\n } else {\n if (file.endsWith('.cts') || file.endsWith('.cjs')) {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: 0,\n text: `const { nxViteTsPaths } = require('@nx/vite/plugins/nx-tsconfig-paths.plugin');\\n`,\n },\n ])\n );\n } else {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: 0,\n text: `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\\n`,\n },\n ])\n );\n }\n }\n}\n\nfunction ensurePluginAdded(tree, file) {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const content = tree.read(file, 'utf-8');\n const ast = tsquery.ast(content);\n const foundDefineConfig = tsquery.query(\n ast,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n if (!foundDefineConfig.length) return content;\n\n // Do not update defineConfig if it has an arrow function since it can be tricky and error-prone.\n const defineUsingArrowFunction = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n if (defineUsingArrowFunction.length) return content;\n\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n const pluginsNode = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])'\n );\n\n if (pluginsNode.length) {\n const updated = tsquery.replace(\n content,\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])',\n (node: Node) => {\n const found = tsquery.query(\n node,\n 'ArrayLiteralExpression'\n ) as ArrayLiteralExpression[];\n let updatedPluginsString = '';\n\n const existingPluginNodes = found?.[0].elements ?? [];\n\n for (const plugin of existingPluginNodes) {\n updatedPluginsString += `${plugin.getText()},`;\n }\n\n if (\n !existingPluginNodes?.some((node: Node) =>\n node.getText().includes('nxViteTsPaths')\n )\n ) {\n updatedPluginsString += ` nxViteTsPaths(),`;\n }\n\n return `plugins: [${updatedPluginsString}]`;\n }\n );\n tree.write(file, updated);\n } else {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: `plugins: [nxViteTsPaths()],\n `,\n },\n ])\n );\n }\n } else {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14, // length of \"defineConfig(\" + 1\n text: `plugins: [nxViteTsPaths()],`,\n },\n ])\n );\n }\n}\n\nexport default setupPathsPlugin;\n"],"names":["setupPathsPlugin","tree","schema","files","globAsync","file","ensureImportExists","ensurePluginAdded","skipFormat","formatFiles","tsquery","require","content","read","ast","allImports","query","length","lastImport","write","applyChangesToString","type","ChangeType","Insert","index","end","text","endsWith","foundDefineConfig","defineUsingArrowFunction","propertyAssignments","pluginsNode","updated","replace","node","found","updatedPluginsString","existingPluginNodes","elements","plugin","getText","some","
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/vite/src/generators/setup-paths-plugin/setup-paths-plugin.ts"],"sourcesContent":["import {\n applyChangesToString,\n ChangeType,\n formatFiles,\n globAsync,\n Tree,\n} from '@nx/devkit';\nimport type { ArrayLiteralExpression, Node } from 'typescript';\n\nexport async function setupPathsPlugin(\n tree: Tree,\n schema: { skipFormat?: boolean }\n) {\n const files = await globAsync(tree, [\n '**/vite.config.{js,ts,mjs,mts,cjs,cts}',\n ]);\n\n for (const file of files) {\n ensureImportExists(tree, file);\n ensurePluginAdded(tree, file);\n }\n\n if (!schema.skipFormat) {\n await formatFiles(tree);\n }\n}\n\nfunction ensureImportExists(tree: Tree, file: string) {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n let content = tree.read(file, 'utf-8');\n const ast = tsquery.ast(content);\n const allImports = tsquery.query(ast, 'ImportDeclaration');\n if (content.includes('@nx/vite/plugins/nx-tsconfig-paths.plugin')) {\n return;\n }\n if (allImports.length) {\n const lastImport = allImports[allImports.length - 1];\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: lastImport.end + 1,\n text: `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\\n`,\n },\n ])\n );\n } else {\n if (file.endsWith('.cts') || file.endsWith('.cjs')) {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: 0,\n text: `const { nxViteTsPaths } = require('@nx/vite/plugins/nx-tsconfig-paths.plugin');\\n`,\n },\n ])\n );\n } else {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: 0,\n text: `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\\n`,\n },\n ])\n );\n }\n }\n}\n\nfunction ensurePluginAdded(tree, file) {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const content = tree.read(file, 'utf-8');\n const ast = tsquery.ast(content);\n const foundDefineConfig = tsquery.query(\n ast,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n if (!foundDefineConfig.length) return content;\n\n // Do not update defineConfig if it has an arrow function since it can be tricky and error-prone.\n const defineUsingArrowFunction = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n if (defineUsingArrowFunction.length) return content;\n\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n const pluginsNode = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])'\n );\n\n if (pluginsNode.length) {\n const updated = tsquery.replace(\n content,\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])',\n (node: Node) => {\n const found = tsquery.query(\n node,\n 'ArrayLiteralExpression'\n ) as ArrayLiteralExpression[];\n let updatedPluginsString = '';\n\n const existingPluginNodes = found?.[0].elements ?? [];\n\n for (const plugin of existingPluginNodes) {\n updatedPluginsString += `${plugin.getText()},`;\n }\n\n if (\n !existingPluginNodes?.some((node: Node) =>\n node.getText().includes('nxViteTsPaths')\n )\n ) {\n updatedPluginsString += ` nxViteTsPaths(),`;\n }\n\n return `plugins: [${updatedPluginsString}]`;\n }\n );\n tree.write(file, updated);\n } else {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: `plugins: [nxViteTsPaths()],\n `,\n },\n ])\n );\n }\n } else {\n tree.write(\n file,\n applyChangesToString(content, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14, // length of \"defineConfig(\" + 1\n text: `plugins: [nxViteTsPaths()],`,\n },\n ])\n );\n }\n}\n\nexport default setupPathsPlugin;\n"],"names":["setupPathsPlugin","tree","schema","files","globAsync","file","ensureImportExists","ensurePluginAdded","skipFormat","formatFiles","tsquery","require","content","read","ast","allImports","query","includes","length","lastImport","write","applyChangesToString","type","ChangeType","Insert","index","end","text","endsWith","foundDefineConfig","defineUsingArrowFunction","propertyAssignments","pluginsNode","updated","replace","node","found","updatedPluginsString","existingPluginNodes","elements","plugin","getText","some","getStart"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IA8JA,OAAgC;eAAhC;;IArJsBA,gBAAgB;eAAhBA;;;wBAHf;AAGA,eAAeA,iBACpBC,IAAU,EACVC,MAAgC;IAEhC,MAAMC,QAAQ,MAAMC,IAAAA,iBAAS,EAACH,MAAM;QAClC;KACD;IAED,KAAK,MAAMI,QAAQF,MAAO;QACxBG,mBAAmBL,MAAMI;QACzBE,kBAAkBN,MAAMI;IAC1B;IAEA,IAAI,CAACH,OAAOM,UAAU,EAAE;QACtB,MAAMC,IAAAA,mBAAW,EAACR;IACpB;AACF;AAEA,SAASK,mBAAmBL,IAAU,EAAEI,IAAY;IAClD,MAAM,EAAEK,OAAO,EAAE,GAAGC,QAAQ;IAC5B,IAAIC,UAAUX,KAAKY,IAAI,CAACR,MAAM;IAC9B,MAAMS,MA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B,CAAC;YACrC;SACD;IAEL;AACF;MAEA,WAAe3B"}
|
package/src/plugins/plugin.js
CHANGED
|
@@ -72,13 +72,19 @@ async function createNodesInternal(configFilePath, options, context, targetsCach
|
|
|
72
72
|
var _;
|
|
73
73
|
(_ = (_targetsCache = targetsCache)[_hash = hash]) != null ? _ : _targetsCache[_hash] = await buildViteTargets(configFilePath, projectRoot, normalizedOptions, context);
|
|
74
74
|
const { targets, metadata } = targetsCache[hash];
|
|
75
|
+
const project = {
|
|
76
|
+
root: projectRoot,
|
|
77
|
+
targets,
|
|
78
|
+
metadata
|
|
79
|
+
};
|
|
80
|
+
// If project is buildable, then the project type.
|
|
81
|
+
// If it is not buildable, then leave it to other plugins/project.json to set the project type.
|
|
82
|
+
if (project.targets[options.buildTargetName]) {
|
|
83
|
+
project.projectType = project.targets[options.serveTargetName] ? 'application' : 'library';
|
|
84
|
+
}
|
|
75
85
|
return {
|
|
76
86
|
projects: {
|
|
77
|
-
[projectRoot]:
|
|
78
|
-
root: projectRoot,
|
|
79
|
-
targets,
|
|
80
|
-
metadata
|
|
81
|
-
}
|
|
87
|
+
[projectRoot]: project
|
|
82
88
|
}
|
|
83
89
|
};
|
|
84
90
|
}
|
|
@@ -103,10 +109,14 @@ async function buildViteTargets(configFilePath, projectRoot, options, context) {
|
|
|
103
109
|
// If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static
|
|
104
110
|
const hasRemixPlugin = viteConfig.plugins && viteConfig.plugins.some((p)=>p.name === 'remix');
|
|
105
111
|
if (!configFilePath.includes('vitest.config') && !hasRemixPlugin && isBuildable) {
|
|
112
|
+
var _viteConfig_build;
|
|
106
113
|
targets[options.buildTargetName] = await buildTarget(options.buildTargetName, namedInputs, buildOutputs, projectRoot);
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
114
|
+
// If running in library mode, then there is nothing to serve.
|
|
115
|
+
if (!((_viteConfig_build = viteConfig.build) == null ? void 0 : _viteConfig_build.lib)) {
|
|
116
|
+
targets[options.serveTargetName] = serveTarget(projectRoot);
|
|
117
|
+
targets[options.previewTargetName] = previewTarget(projectRoot);
|
|
118
|
+
targets[options.serveStaticTargetName] = serveStaticTarget(options);
|
|
119
|
+
}
|
|
110
120
|
}
|
|
111
121
|
// if file is vitest.config or vite.config has definition for test, create target for test
|
|
112
122
|
if (configFilePath.includes('vitest.config') || hasTest) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/vite/src/plugins/plugin.ts"],"sourcesContent":["import {\n CreateDependencies,\n CreateNodes,\n CreateNodesContext,\n createNodesFromFiles,\n CreateNodesV2,\n detectPackageManager,\n joinPathFragments,\n logger,\n ProjectConfiguration,\n readJsonFile,\n TargetConfiguration,\n writeJsonFile,\n} from '@nx/devkit';\nimport { dirname, isAbsolute, join, relative } from 'path';\nimport { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';\nimport { existsSync, readdirSync } from 'fs';\nimport { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';\nimport { workspaceDataDirectory } from 'nx/src/utils/cache-directory';\nimport { getLockFileName } from '@nx/js';\nimport { loadViteDynamicImport } from '../utils/executor-utils';\nimport { hashObject } from 'nx/src/hasher/file-hasher';\n\nexport interface VitePluginOptions {\n buildTargetName?: string;\n testTargetName?: string;\n serveTargetName?: string;\n previewTargetName?: string;\n serveStaticTargetName?: string;\n}\ntype ViteTargets = Pick<ProjectConfiguration, 'targets' | 'metadata'>;\n\nfunction readTargetsCache(cachePath: string): Record<string, ViteTargets> {\n return existsSync(cachePath) ? readJsonFile(cachePath) : {};\n}\n\nfunction writeTargetsToCache(cachePath, results?: Record<string, ViteTargets>) {\n writeJsonFile(cachePath, results);\n}\n\n/**\n * @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.\n */\nexport const createDependencies: CreateDependencies = () => {\n return [];\n};\n\nconst viteVitestConfigGlob = '**/{vite,vitest}.config.{js,ts,mjs,mts,cjs,cts}';\n\nexport const createNodesV2: CreateNodesV2<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePaths, options, context) => {\n const optionsHash = hashObject(options);\n const cachePath = join(workspaceDataDirectory, `vite-${optionsHash}.hash`);\n const targetsCache = readTargetsCache(cachePath);\n try {\n return await createNodesFromFiles(\n (configFile, options, context) =>\n createNodesInternal(configFile, options, context, targetsCache),\n configFilePaths,\n options,\n context\n );\n } finally {\n writeTargetsToCache(cachePath, targetsCache);\n }\n },\n];\n\nexport const createNodes: CreateNodes<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePath, options, context) => {\n logger.warn(\n '`createNodes` is deprecated. Update your plugin to utilize createNodesV2 instead. In Nx 20, this will change to the createNodesV2 API.'\n );\n return createNodesInternal(configFilePath, options, context, {});\n },\n];\n\nasync function createNodesInternal(\n configFilePath: string,\n options: VitePluginOptions,\n context: CreateNodesContext,\n targetsCache: Record<string, ViteTargets>\n) {\n const projectRoot = dirname(configFilePath);\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot));\n if (\n !siblingFiles.includes('package.json') &&\n !siblingFiles.includes('project.json')\n ) {\n return {};\n }\n\n const normalizedOptions = normalizeOptions(options);\n\n // We do not want to alter how the hash is calculated, so appending the config file path to the hash\n // to prevent vite/vitest files overwriting the target cache created by the other\n const hash =\n (await calculateHashForCreateNodes(\n projectRoot,\n normalizedOptions,\n context,\n [getLockFileName(detectPackageManager(context.workspaceRoot))]\n )) + configFilePath;\n\n targetsCache[hash] ??= await buildViteTargets(\n configFilePath,\n projectRoot,\n normalizedOptions,\n context\n );\n\n const { targets, metadata } = targetsCache[hash];\n\n return {\n projects: {\n [projectRoot]: {\n root: projectRoot,\n targets,\n metadata,\n },\n },\n };\n}\n\nasync function buildViteTargets(\n configFilePath: string,\n projectRoot: string,\n options: VitePluginOptions,\n context: CreateNodesContext\n): Promise<ViteTargets> {\n const absoluteConfigFilePath = joinPathFragments(\n context.workspaceRoot,\n configFilePath\n );\n\n // Workaround for the `build$3 is not a function` error that we sometimes see in agents.\n // This should be removed later once we address the issue properly\n try {\n const importEsbuild = () => new Function('return import(\"esbuild\")')();\n await importEsbuild();\n } catch {\n // do nothing\n }\n const { resolveConfig } = await loadViteDynamicImport();\n const viteConfig = await resolveConfig(\n {\n configFile: absoluteConfigFilePath,\n mode: 'development',\n },\n 'build'\n );\n\n const { buildOutputs, testOutputs, hasTest, isBuildable } = getOutputs(\n viteConfig,\n projectRoot,\n context.workspaceRoot\n );\n\n const namedInputs = getNamedInputs(projectRoot, context);\n\n const targets: Record<string, TargetConfiguration> = {};\n\n // If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static\n const hasRemixPlugin =\n viteConfig.plugins && viteConfig.plugins.some((p) => p.name === 'remix');\n if (\n !configFilePath.includes('vitest.config') &&\n !hasRemixPlugin &&\n isBuildable\n ) {\n targets[options.buildTargetName] = await buildTarget(\n options.buildTargetName,\n namedInputs,\n buildOutputs,\n projectRoot\n );\n\n targets[options.serveTargetName] = serveTarget(projectRoot);\n\n targets[options.previewTargetName] = previewTarget(projectRoot);\n\n targets[options.serveStaticTargetName] = serveStaticTarget(options) as {};\n }\n\n // if file is vitest.config or vite.config has definition for test, create target for test\n if (configFilePath.includes('vitest.config') || hasTest) {\n targets[options.testTargetName] = await testTarget(\n namedInputs,\n testOutputs,\n projectRoot\n );\n }\n\n const metadata = {};\n return { targets, metadata };\n}\n\nasync function buildTarget(\n buildTargetName: string,\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string\n) {\n return {\n command: `vite build`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n dependsOn: [`^${buildTargetName}`],\n inputs: [\n ...('production' in namedInputs\n ? ['production', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vite'],\n },\n ],\n outputs,\n };\n}\n\nfunction serveTarget(projectRoot: string) {\n const targetConfig: TargetConfiguration = {\n command: `vite serve`,\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n };\n\n return targetConfig;\n}\n\nfunction previewTarget(projectRoot: string) {\n const targetConfig: TargetConfiguration = {\n command: `vite preview`,\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n };\n\n return targetConfig;\n}\n\nasync function testTarget(\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string\n) {\n return {\n command: `vitest`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n inputs: [\n ...('production' in namedInputs\n ? ['default', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vitest'],\n },\n { env: 'CI' },\n ],\n outputs,\n };\n}\n\nfunction serveStaticTarget(options: VitePluginOptions) {\n const targetConfig: TargetConfiguration = {\n executor: '@nx/web:file-server',\n options: {\n buildTarget: `${options.buildTargetName}`,\n spa: true,\n },\n };\n\n return targetConfig;\n}\n\nfunction getOutputs(\n viteConfig: Record<string, any> | undefined,\n projectRoot: string,\n workspaceRoot: string\n): {\n buildOutputs: string[];\n testOutputs: string[];\n hasTest: boolean;\n isBuildable: boolean;\n} {\n const { build, test } = viteConfig;\n\n const buildOutputPath = normalizeOutputPath(\n build?.outDir,\n projectRoot,\n workspaceRoot,\n 'dist'\n );\n\n const isBuildable =\n build?.lib ||\n build?.rollupOptions?.inputs ||\n existsSync(join(workspaceRoot, projectRoot, 'index.html'));\n\n const reportsDirectoryPath = normalizeOutputPath(\n test?.coverage?.reportsDirectory,\n projectRoot,\n workspaceRoot,\n 'coverage'\n );\n\n return {\n buildOutputs: [buildOutputPath],\n testOutputs: [reportsDirectoryPath],\n hasTest: !!test,\n isBuildable,\n };\n}\n\nfunction normalizeOutputPath(\n outputPath: string | undefined,\n projectRoot: string,\n workspaceRoot: string,\n path: 'coverage' | 'dist'\n): string | undefined {\n if (!outputPath) {\n if (projectRoot === '.') {\n return `{projectRoot}/${path}`;\n } else {\n return `{workspaceRoot}/${path}/{projectRoot}`;\n }\n } else {\n if (isAbsolute(outputPath)) {\n return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`;\n } else {\n if (outputPath.startsWith('..')) {\n return join('{workspaceRoot}', join(projectRoot, outputPath));\n } else {\n return join('{projectRoot}', outputPath);\n }\n }\n }\n}\n\nfunction normalizeOptions(options: VitePluginOptions): VitePluginOptions {\n options ??= {};\n options.buildTargetName ??= 'build';\n options.serveTargetName ??= 'serve';\n options.previewTargetName ??= 'preview';\n options.testTargetName ??= 'test';\n options.serveStaticTargetName ??= 'serve-static';\n return options;\n}\n"],"names":["createDependencies","createNodes","createNodesV2","readTargetsCache","cachePath","existsSync","readJsonFile","writeTargetsToCache","results","writeJsonFile","viteVitestConfigGlob","configFilePaths","options","context","optionsHash","hashObject","join","workspaceDataDirectory","targetsCache","createNodesFromFiles","configFile","createNodesInternal","configFilePath","logger","warn","hash","projectRoot","dirname","siblingFiles","readdirSync","workspaceRoot","includes","normalizedOptions","normalizeOptions","calculateHashForCreateNodes","getLockFileName","detectPackageManager","buildViteTargets","targets","metadata","projects","root","absoluteConfigFilePath","joinPathFragments","importEsbuild","Function","resolveConfig","loadViteDynamicImport","viteConfig","mode","buildOutputs","testOutputs","hasTest","isBuildable","getOutputs","namedInputs","getNamedInputs","hasRemixPlugin","plugins","some","p","name","buildTargetName","buildTarget","serveTargetName","serveTarget","previewTargetName","previewTarget","serveStaticTargetName","serveStaticTarget","testTargetName","testTarget","outputs","command","cwd","cache","dependsOn","inputs","externalDependencies","targetConfig","env","executor","spa","build","test","buildOutputPath","normalizeOutputPath","outDir","lib","rollupOptions","reportsDirectoryPath","coverage","reportsDirectory","outputPath","path","isAbsolute","relative","startsWith"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAgB;QAC/BlC,aAAa;YAACuC;SAAqB;QACnCtC,SAAS,CAAC,CAACgC;QACX/B;IACF;AACF;AAEA,SAASiC,oBACPO,UAA8B,EAC9BnE,WAAmB,EACnBI,aAAqB,EACrBgE,IAAyB;IAEzB,IAAI,CAACD,YAAY;QACf,IAAInE,gBAAgB,KAAK;YACvB,OAAO,CAAC,cAAc,EAAEoE,KAAK,CAAC;QAChC,OAAO;YACL,OAAO,CAAC,gBAAgB,EAAEA,KAAK,cAAc,CAAC;QAChD;IACF,OAAO;QACL,IAAIC,IAAAA,gBAAU,EAACF,aAAa;YAC1B,OAAO,CAAC,gBAAgB,EAAEG,IAAAA,cAAQ,EAAClE,eAAe+D,YAAY,CAAC;QACjE,OAAO;YACL,IAAIA,WAAWI,UAAU,CAAC,OAAO;gBAC/B,OAAOjF,IAAAA,UAAI,EAAC,mBAAmBA,IAAAA,UAAI,EAACU,aAAamE;YACnD,OAAO;gBACL,OAAO7E,IAAAA,UAAI,EAAC,iBAAiB6E;YAC/B;QACF;IACF;AACF;AAEA,SAAS5D,iBAAiBrB,OAA0B;QAElDA,UACAA,WACAA,WACAA,WACAA;IALAA,kBAAAA,UAAAA,UAAY,CAAC;;IACbA,qBAAAA,WAAAA,SAAQkD,8CAARlD,SAAQkD,kBAAoB;;IAC5BlD,qBAAAA,YAAAA,SAAQoD,8CAARpD,UAAQoD,kBAAoB;;IAC5BpD,uBAAAA,YAAAA,SAAQsD,kDAARtD,UAAQsD,oBAAsB;;IAC9BtD,oBAAAA,YAAAA,SAAQ0D,4CAAR1D,UAAQ0D,iBAAmB;;IAC3B1D,2BAAAA,YAAAA,SAAQwD,0DAARxD,UAAQwD,wBAA0B;IAClC,OAAOxD;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/vite/src/plugins/plugin.ts"],"sourcesContent":["import {\n CreateDependencies,\n CreateNodes,\n CreateNodesContext,\n createNodesFromFiles,\n CreateNodesV2,\n detectPackageManager,\n joinPathFragments,\n logger,\n ProjectConfiguration,\n readJsonFile,\n TargetConfiguration,\n writeJsonFile,\n} from '@nx/devkit';\nimport { dirname, isAbsolute, join, relative } from 'path';\nimport { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';\nimport { existsSync, readdirSync } from 'fs';\nimport { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';\nimport { workspaceDataDirectory } from 'nx/src/utils/cache-directory';\nimport { getLockFileName } from '@nx/js';\nimport { loadViteDynamicImport } from '../utils/executor-utils';\nimport { hashObject } from 'nx/src/hasher/file-hasher';\n\nexport interface VitePluginOptions {\n buildTargetName?: string;\n testTargetName?: string;\n serveTargetName?: string;\n previewTargetName?: string;\n serveStaticTargetName?: string;\n}\ntype ViteTargets = Pick<ProjectConfiguration, 'targets' | 'metadata'>;\n\nfunction readTargetsCache(cachePath: string): Record<string, ViteTargets> {\n return existsSync(cachePath) ? readJsonFile(cachePath) : {};\n}\n\nfunction writeTargetsToCache(cachePath, results?: Record<string, ViteTargets>) {\n writeJsonFile(cachePath, results);\n}\n\n/**\n * @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.\n */\nexport const createDependencies: CreateDependencies = () => {\n return [];\n};\n\nconst viteVitestConfigGlob = '**/{vite,vitest}.config.{js,ts,mjs,mts,cjs,cts}';\n\nexport const createNodesV2: CreateNodesV2<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePaths, options, context) => {\n const optionsHash = hashObject(options);\n const cachePath = join(workspaceDataDirectory, `vite-${optionsHash}.hash`);\n const targetsCache = readTargetsCache(cachePath);\n try {\n return await createNodesFromFiles(\n (configFile, options, context) =>\n createNodesInternal(configFile, options, context, targetsCache),\n configFilePaths,\n options,\n context\n );\n } finally {\n writeTargetsToCache(cachePath, targetsCache);\n }\n },\n];\n\nexport const createNodes: CreateNodes<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePath, options, context) => {\n logger.warn(\n '`createNodes` is deprecated. Update your plugin to utilize createNodesV2 instead. In Nx 20, this will change to the createNodesV2 API.'\n );\n return createNodesInternal(configFilePath, options, context, {});\n },\n];\n\nasync function createNodesInternal(\n configFilePath: string,\n options: VitePluginOptions,\n context: CreateNodesContext,\n targetsCache: Record<string, ViteTargets>\n) {\n const projectRoot = dirname(configFilePath);\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot));\n if (\n !siblingFiles.includes('package.json') &&\n !siblingFiles.includes('project.json')\n ) {\n return {};\n }\n\n const normalizedOptions = normalizeOptions(options);\n\n // We do not want to alter how the hash is calculated, so appending the config file path to the hash\n // to prevent vite/vitest files overwriting the target cache created by the other\n const hash =\n (await calculateHashForCreateNodes(\n projectRoot,\n normalizedOptions,\n context,\n [getLockFileName(detectPackageManager(context.workspaceRoot))]\n )) + configFilePath;\n\n targetsCache[hash] ??= await buildViteTargets(\n configFilePath,\n projectRoot,\n normalizedOptions,\n context\n );\n\n const { targets, metadata } = targetsCache[hash];\n const project: ProjectConfiguration = {\n root: projectRoot,\n targets,\n metadata,\n };\n\n // If project is buildable, then the project type.\n // If it is not buildable, then leave it to other plugins/project.json to set the project type.\n if (project.targets[options.buildTargetName]) {\n project.projectType = project.targets[options.serveTargetName]\n ? 'application'\n : 'library';\n }\n\n return {\n projects: {\n [projectRoot]: project,\n },\n };\n}\n\nasync function buildViteTargets(\n configFilePath: string,\n projectRoot: string,\n options: VitePluginOptions,\n context: CreateNodesContext\n): Promise<ViteTargets> {\n const absoluteConfigFilePath = joinPathFragments(\n context.workspaceRoot,\n configFilePath\n );\n // Workaround for the `build$3 is not a function` error that we sometimes see in agents.\n // This should be removed later once we address the issue properly\n try {\n const importEsbuild = () => new Function('return import(\"esbuild\")')();\n await importEsbuild();\n } catch {\n // do nothing\n }\n const { resolveConfig } = await loadViteDynamicImport();\n const viteConfig = await resolveConfig(\n {\n configFile: absoluteConfigFilePath,\n mode: 'development',\n },\n 'build'\n );\n\n const { buildOutputs, testOutputs, hasTest, isBuildable } = getOutputs(\n viteConfig,\n projectRoot,\n context.workspaceRoot\n );\n\n const namedInputs = getNamedInputs(projectRoot, context);\n\n const targets: Record<string, TargetConfiguration> = {};\n\n // If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static\n const hasRemixPlugin =\n viteConfig.plugins && viteConfig.plugins.some((p) => p.name === 'remix');\n if (\n !configFilePath.includes('vitest.config') &&\n !hasRemixPlugin &&\n isBuildable\n ) {\n targets[options.buildTargetName] = await buildTarget(\n options.buildTargetName,\n namedInputs,\n buildOutputs,\n projectRoot\n );\n\n // If running in library mode, then there is nothing to serve.\n if (!viteConfig.build?.lib) {\n targets[options.serveTargetName] = serveTarget(projectRoot);\n targets[options.previewTargetName] = previewTarget(projectRoot);\n targets[options.serveStaticTargetName] = serveStaticTarget(options) as {};\n }\n }\n\n // if file is vitest.config or vite.config has definition for test, create target for test\n if (configFilePath.includes('vitest.config') || hasTest) {\n targets[options.testTargetName] = await testTarget(\n namedInputs,\n testOutputs,\n projectRoot\n );\n }\n\n const metadata = {};\n return { targets, metadata };\n}\n\nasync function buildTarget(\n buildTargetName: string,\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string\n) {\n return {\n command: `vite build`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n dependsOn: [`^${buildTargetName}`],\n inputs: [\n ...('production' in namedInputs\n ? ['production', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vite'],\n },\n ],\n outputs,\n };\n}\n\nfunction serveTarget(projectRoot: string) {\n const targetConfig: TargetConfiguration = {\n command: `vite serve`,\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n };\n\n return targetConfig;\n}\n\nfunction previewTarget(projectRoot: string) {\n const targetConfig: TargetConfiguration = {\n command: `vite preview`,\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n };\n\n return targetConfig;\n}\n\nasync function testTarget(\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string\n) {\n return {\n command: `vitest`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n inputs: [\n ...('production' in namedInputs\n ? ['default', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vitest'],\n },\n { env: 'CI' },\n ],\n outputs,\n };\n}\n\nfunction serveStaticTarget(options: VitePluginOptions) {\n const targetConfig: TargetConfiguration = {\n executor: '@nx/web:file-server',\n options: {\n buildTarget: `${options.buildTargetName}`,\n spa: true,\n },\n };\n\n return targetConfig;\n}\n\nfunction getOutputs(\n viteConfig: Record<string, any> | undefined,\n projectRoot: string,\n workspaceRoot: string\n): {\n buildOutputs: string[];\n testOutputs: string[];\n hasTest: boolean;\n isBuildable: boolean;\n} {\n const { build, test } = viteConfig;\n\n const buildOutputPath = normalizeOutputPath(\n build?.outDir,\n projectRoot,\n workspaceRoot,\n 'dist'\n );\n\n const isBuildable =\n build?.lib ||\n build?.rollupOptions?.inputs ||\n existsSync(join(workspaceRoot, projectRoot, 'index.html'));\n\n const reportsDirectoryPath = normalizeOutputPath(\n test?.coverage?.reportsDirectory,\n projectRoot,\n workspaceRoot,\n 'coverage'\n );\n\n return {\n buildOutputs: [buildOutputPath],\n testOutputs: [reportsDirectoryPath],\n hasTest: !!test,\n isBuildable,\n };\n}\n\nfunction normalizeOutputPath(\n outputPath: string | undefined,\n projectRoot: string,\n workspaceRoot: string,\n path: 'coverage' | 'dist'\n): string | undefined {\n if (!outputPath) {\n if (projectRoot === '.') {\n return `{projectRoot}/${path}`;\n } else {\n return `{workspaceRoot}/${path}/{projectRoot}`;\n }\n } else {\n if (isAbsolute(outputPath)) {\n return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`;\n } else {\n if (outputPath.startsWith('..')) {\n return join('{workspaceRoot}', join(projectRoot, outputPath));\n } else {\n return join('{projectRoot}', outputPath);\n }\n }\n }\n}\n\nfunction normalizeOptions(options: VitePluginOptions): VitePluginOptions {\n options ??= {};\n options.buildTargetName ??= 'build';\n options.serveTargetName ??= 'serve';\n options.previewTargetName ??= 'preview';\n options.testTargetName ??= 'test';\n options.serveStaticTargetName ??= 'serve-static';\n return options;\n}\n"],"names":["createDependencies","createNodes","createNodesV2","readTargetsCache","cachePath","existsSync","readJsonFile","writeTargetsToCache","results","writeJsonFile","viteVitestConfigGlob","configFilePaths","options","context","optionsHash","hashObject","join","workspaceDataDirectory","targetsCache","createNodesFromFiles","configFile","createNodesInternal","configFilePath","logger","warn","hash","projectRoot","dirname","siblingFiles","readdirSync","workspaceRoot","includes","normalizedOptions","normalizeOptions","calculateHashForCreateNodes","getLockFileName","detectPackageManager","buildViteTargets","targets","metadata","project","root","buildTargetName","projectType","serveTargetName","projects","absoluteConfigFilePath","joinPathFragments","importEsbuild","Function","resolveConfig","loadViteDynamicImport","viteConfig","mode","buildOutputs","testOutputs","hasTest","isBuildable","getOutputs","namedInputs","getNamedInputs","hasRemixPlugin","plugins","some","p","name","buildTarget","build","lib","serveTarget","previewTargetName","previewTarget","serveStaticTargetName","serveStaticTarget","testTargetName","testTarget","outputs","command","cwd","cache","dependsOn","inputs","externalDependencies","targetConfig","env","executor","spa","test","buildOutputPath","normalizeOutputPath","outDir","rollupOptions","reportsDirectoryPath","coverage","reportsDirectory","outputPath","path","isAbsolute","relative","startsWith"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IA2CaA,kBAAkB;eAAlBA;;IA0BAC,WAAW;eAAXA;;IApBAC,aAAa;eAAbA;;;wBApCN;sBAC6C;gCACrB;oBACS;6CACI;gCACL;oBACP;+BAC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