@nx/vite 19.3.1 → 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 +1 -1
- 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/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",
|
|
@@ -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}`;
|
|
@@ -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 (\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 );\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,M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G,aAAaC,IAAAA,yBAAiB,EAClCP,SAAS1B,eAAe,EACxBC,KAAK,CAAC,EAAE,CAAC6B,OAAO,CAAC,SAAS;gBAG5BxB,eAAe4B,SACb7B,WAAWyB,OAAO,CAACD,kBAAkBG;YAEzC;QACF;QAEA,OAAO1B;IACT;IAEA,SAAS4B,SAASC,IAAY;QAC5B,KAAK,MAAMC,OAAOzF,QAAQK,UAAU,CAAE;YACpC,MAAMqF,eAAexB,IAAAA,iBAAO,EAACsB,OAAOC;YACpC,IAAItB,IAAAA,kBAAU,EAACuB,eAAe;gBAC5B,OAAOA;YACT;YAEA,MAAMC,oBAAoBzB,IAAAA,iBAAO,EAACsB,MAAM,CAAC,KAAK,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;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,mBAAmB;gBAC3C,MAAMG,aAAaC,IAAAA,yBAAiB,EAClCP,SAAS1B,eAAe,EACxBC,KAAK,CAAC,EAAE,CAAC6B,OAAO,CAAC,SAAS;gBAG5BxB,eAAe4B,SACb7B,WAAWyB,OAAO,CAACD,kBAAkBG;YAEzC;QACF;QAEA,OAAO1B;IACT;IAEA,SAAS4B,SAASC,IAAY;QAC5B,KAAK,MAAMC,OAAOzF,QAAQK,UAAU,CAAE;YACpC,MAAMqF,eAAexB,IAAAA,iBAAO,EAACsB,OAAOC;YACpC,IAAItB,IAAAA,kBAAU,EAACuB,eAAe;gBAC5B,OAAOA;YACT;YAEA,MAAMC,oBAAoBzB,IAAAA,iBAAO,EAACsB,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,WAA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AiB;gBAAC;gBAAS;gBAAc;aAAa;YACtDC,mBAAmB;gBAAC;gBAAW;gBAAgB;aAAe;YAC9DC,uBAAuB;gBACrB;gBACA;gBACA;aACD;QACH,GACAb,OAAOc,oBAAoB;IAE/B;IAEAlC,qBAAqBC;IAErB,IAAImB,OAAOe,gBAAgB,EAAE;QAC3B,MAAMA,IAAAA,kCAAgB,EAAClC,MAAM;YAAEmC,YAAY;QAAK;IAClD;IAEA,MAAMC,QAA6B,EAAE;IACrC,IAAI,CAACjB,OAAOkB,eAAe,EAAE;QAC3BD,MAAM9B,IAAI,CAACgC,IAAAA,4BAAqB,EAACtC;QACjCoC,MAAM9B,IAAI,CAACiC,IAAAA,iCAA0B,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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