@nx/vite 21.0.0-beta.1 → 21.0.0-beta.3
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/migrations.json +41 -0
- package/package.json +7 -6
- package/plugins/nx-copy-assets.plugin.js +3 -2
- package/plugins/nx-copy-assets.plugin.js.map +1 -1
- package/plugins/nx-tsconfig-paths.plugin.d.ts +2 -1
- package/plugins/nx-tsconfig-paths.plugin.js +14 -8
- package/plugins/nx-tsconfig-paths.plugin.js.map +1 -1
- package/src/executors/build/build.impl.d.ts +2 -4
- package/src/executors/build/build.impl.js +86 -70
- package/src/executors/build/build.impl.js.map +1 -1
- package/src/executors/build/schema.d.ts +1 -0
- package/src/executors/build/schema.json +6 -0
- package/src/executors/test/lib/utils.js +9 -2
- package/src/executors/test/lib/utils.js.map +1 -1
- package/src/generators/configuration/configuration.js +7 -1
- package/src/generators/configuration/configuration.js.map +1 -1
- package/src/generators/init/init.js +3 -3
- package/src/generators/init/init.js.map +1 -1
- package/src/generators/init/lib/utils.d.ts +1 -1
- package/src/generators/init/lib/utils.js +7 -4
- package/src/generators/init/lib/utils.js.map +1 -1
- package/src/generators/init/schema.d.ts +2 -0
- package/src/generators/init/schema.json +7 -0
- package/src/generators/vitest/vitest-generator.js +23 -11
- package/src/generators/vitest/vitest-generator.js.map +1 -1
- package/src/migrations/update-17-2-0/lib/edit-test-config.js +2 -2
- package/src/migrations/update-17-2-0/lib/edit-test-config.js.map +1 -1
- package/src/migrations/update-20-0-4/add-vite-temp-files-to-git-ignore.js +2 -2
- package/src/migrations/update-20-0-4/add-vite-temp-files-to-git-ignore.js.map +1 -1
- package/src/migrations/update-20-3-0/add-vitest-temp-files-to-git-ignore.js +2 -2
- package/src/migrations/update-20-3-0/add-vitest-temp-files-to-git-ignore.js.map +1 -1
- package/src/migrations/update-20-5-0/eslint-ignore-vite-temp-files.d.ts +2 -0
- package/src/migrations/update-20-5-0/eslint-ignore-vite-temp-files.js +47 -0
- package/src/migrations/update-20-5-0/eslint-ignore-vite-temp-files.js.map +1 -0
- package/src/migrations/update-20-5-0/install-jiti.d.ts +2 -0
- package/src/migrations/update-20-5-0/install-jiti.js +17 -0
- package/src/migrations/update-20-5-0/install-jiti.js.map +1 -0
- package/src/migrations/update-20-5-0/update-resolve-conditions.d.ts +2 -0
- package/src/migrations/update-20-5-0/update-resolve-conditions.js +72 -0
- package/src/migrations/update-20-5-0/update-resolve-conditions.js.map +1 -0
- package/src/plugins/plugin.js +107 -49
- package/src/plugins/plugin.js.map +1 -1
- package/src/utils/e2e-web-server-info-utils.d.ts +1 -0
- package/src/utils/e2e-web-server-info-utils.js +27 -3
- package/src/utils/e2e-web-server-info-utils.js.map +1 -1
- package/src/utils/generator-utils.js +6 -6
- package/src/utils/generator-utils.js.map +1 -1
- package/src/utils/ignore-vite-temp-files.d.ts +4 -0
- package/src/utils/ignore-vite-temp-files.js +71 -0
- package/src/utils/ignore-vite-temp-files.js.map +1 -0
- package/src/utils/version-utils.d.ts +11 -0
- package/src/utils/version-utils.js +68 -0
- package/src/utils/version-utils.js.map +1 -0
- package/src/utils/versions.d.ts +11 -6
- package/src/utils/versions.js +26 -6
- package/src/utils/versions.js.map +1 -1
- package/src/utils/vite-config-edit-utils.js +25 -1
- package/src/utils/vite-config-edit-utils.js.map +1 -1
- package/src/utils/add-vite-temp-files-to-gitignore.d.ts +0 -2
- package/src/utils/add-vite-temp-files-to-gitignore.js +0 -34
- package/src/utils/add-vite-temp-files-to-gitignore.js.map +0 -1
package/migrations.json
CHANGED
|
@@ -34,9 +34,50 @@
|
|
|
34
34
|
"version": "20.3.0-beta.2",
|
|
35
35
|
"description": "Add gitignore entry for temporary vitest config files.",
|
|
36
36
|
"implementation": "./src/migrations/update-20-3-0/add-vitest-temp-files-to-git-ignore"
|
|
37
|
+
},
|
|
38
|
+
"update-20-5-0-install-jiti": {
|
|
39
|
+
"version": "20.5.0-beta.2",
|
|
40
|
+
"description": "Install jiti as a devDependency to allow vite to parse TS postcss files.",
|
|
41
|
+
"implementation": "./src/migrations/update-20-5-0/install-jiti"
|
|
42
|
+
},
|
|
43
|
+
"update-20-5-0-update-resolve-conditions": {
|
|
44
|
+
"version": "20.5.0-beta.3",
|
|
45
|
+
"description": "Update resolve.conditions to include defaults that are no longer provided by Vite.",
|
|
46
|
+
"implementation": "./src/migrations/update-20-5-0/update-resolve-conditions"
|
|
47
|
+
},
|
|
48
|
+
"eslint-ignore-vite-temp-files": {
|
|
49
|
+
"version": "20.5.0-beta.3",
|
|
50
|
+
"description": "Add vite config temporary files to the ESLint configuration ignore patterns if ESLint is used.",
|
|
51
|
+
"implementation": "./src/migrations/update-20-5-0/eslint-ignore-vite-temp-files"
|
|
37
52
|
}
|
|
38
53
|
},
|
|
39
54
|
"packageJsonUpdates": {
|
|
55
|
+
"20.7.1": {
|
|
56
|
+
"version": "20.7.1-beta.0",
|
|
57
|
+
"packages": {
|
|
58
|
+
"@analogjs/vite-plugin-angular": {
|
|
59
|
+
"version": "~1.14.1",
|
|
60
|
+
"alwaysAddToPackageJson": false
|
|
61
|
+
},
|
|
62
|
+
"@analogjs/vitest-angular": {
|
|
63
|
+
"version": "~1.14.1",
|
|
64
|
+
"alwaysAddToPackageJson": false
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"20.5.0": {
|
|
69
|
+
"version": "20.5.0-beta.3",
|
|
70
|
+
"packages": {
|
|
71
|
+
"vite": {
|
|
72
|
+
"version": "^6.0.0",
|
|
73
|
+
"alwaysAddToPackageJson": false
|
|
74
|
+
},
|
|
75
|
+
"vite-plugin-dts": {
|
|
76
|
+
"version": "~4.5.0",
|
|
77
|
+
"alwaysAddToPackageJson": false
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
},
|
|
40
81
|
"18.1.0": {
|
|
41
82
|
"version": "18.1.0-beta.1",
|
|
42
83
|
"packages": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nx/vite",
|
|
3
|
-
"version": "21.0.0-beta.
|
|
3
|
+
"version": "21.0.0-beta.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "The Nx Plugin for building and testing applications using Vite",
|
|
6
6
|
"repository": {
|
|
@@ -30,17 +30,18 @@
|
|
|
30
30
|
"migrations": "./migrations.json"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@nx/devkit": "21.0.0-beta.
|
|
33
|
+
"@nx/devkit": "21.0.0-beta.3",
|
|
34
34
|
"@phenomnomnominal/tsquery": "~5.0.1",
|
|
35
35
|
"@swc/helpers": "~0.5.0",
|
|
36
36
|
"enquirer": "~2.3.6",
|
|
37
|
-
"@nx/js": "21.0.0-beta.
|
|
37
|
+
"@nx/js": "21.0.0-beta.3",
|
|
38
38
|
"tsconfig-paths": "^4.1.2",
|
|
39
|
-
"minimatch": "9.0.3"
|
|
39
|
+
"minimatch": "9.0.3",
|
|
40
|
+
"semver": "^7.6.3"
|
|
40
41
|
},
|
|
41
42
|
"peerDependencies": {
|
|
42
|
-
"vite": "^5.0.0",
|
|
43
|
-
"vitest": "^1.3.1 || ^2.0.0"
|
|
43
|
+
"vite": "^5.0.0 || ^6.0.0",
|
|
44
|
+
"vitest": "^1.3.1 || ^2.0.0 || ^3.0.0"
|
|
44
45
|
},
|
|
45
46
|
"publishConfig": {
|
|
46
47
|
"access": "public"
|
|
@@ -13,6 +13,7 @@ function nxCopyAssetsPlugin(_assets) {
|
|
|
13
13
|
let config;
|
|
14
14
|
let handler;
|
|
15
15
|
let dispose;
|
|
16
|
+
if (global.NX_GRAPH_CREATION) return;
|
|
16
17
|
return {
|
|
17
18
|
name: 'nx-copy-assets-plugin',
|
|
18
19
|
configResolved (_config) {
|
|
@@ -32,10 +33,10 @@ function nxCopyAssetsPlugin(_assets) {
|
|
|
32
33
|
handler = new _copyassetshandler.CopyAssetsHandler({
|
|
33
34
|
rootDir: _devkit.workspaceRoot,
|
|
34
35
|
projectDir: config.root,
|
|
35
|
-
outputDir: (0, _nodepath.join)(config.root, config.build.outDir),
|
|
36
|
+
outputDir: config.build.outDir.startsWith(config.root) ? config.build.outDir : (0, _nodepath.join)(config.root, config.build.outDir),
|
|
36
37
|
assets
|
|
37
38
|
});
|
|
38
|
-
if (this.meta.watchMode) {
|
|
39
|
+
if (this.meta.watchMode && (0, _devkit.isDaemonEnabled)()) {
|
|
39
40
|
dispose = await handler.watchAndProcessOnAssetChange();
|
|
40
41
|
}
|
|
41
42
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../packages/vite/plugins/nx-copy-assets.plugin.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { joinPathFragments, workspaceRoot } from '@nx/devkit';\nimport { AssetGlob } from '@nx/js/src/utils/assets/assets';\nimport { CopyAssetsHandler } from '@nx/js/src/utils/assets/copy-assets-handler';\n\nexport function nxCopyAssetsPlugin(_assets: (string | AssetGlob)[]): Plugin {\n let config: ResolvedConfig;\n let handler: CopyAssetsHandler;\n let dispose: () => void;\n\n return {\n name: 'nx-copy-assets-plugin',\n configResolved(_config) {\n config = _config;\n },\n async buildStart() {\n const relativeProjectRoot = relative(workspaceRoot, config.root);\n const assets = _assets.map((a) => {\n if (typeof a === 'string') {\n return joinPathFragments(relativeProjectRoot, a);\n } else {\n return {\n ...a,\n input: joinPathFragments(relativeProjectRoot, a.input),\n };\n }\n });\n handler = new CopyAssetsHandler({\n rootDir: workspaceRoot,\n projectDir: config.root,\n outputDir: join(config.root, config.build.outDir),\n assets,\n });\n if (this.meta.watchMode) {\n dispose = await handler.watchAndProcessOnAssetChange();\n }\n },\n async writeBundle() {\n await handler.processAllAssetsOnce();\n },\n async closeWatcher() {\n dispose == null ? void 0 : dispose();\n },\n };\n}\n"],"names":["nxCopyAssetsPlugin","_assets","config","handler","dispose","name","configResolved","_config","buildStart","relativeProjectRoot","relative","workspaceRoot","root","assets","map","a","joinPathFragments","input","CopyAssetsHandler","rootDir","projectDir","outputDir","
|
|
1
|
+
{"version":3,"sources":["../../../../packages/vite/plugins/nx-copy-assets.plugin.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { isDaemonEnabled, joinPathFragments, workspaceRoot } from '@nx/devkit';\nimport { AssetGlob } from '@nx/js/src/utils/assets/assets';\nimport { CopyAssetsHandler } from '@nx/js/src/utils/assets/copy-assets-handler';\n\nexport function nxCopyAssetsPlugin(_assets: (string | AssetGlob)[]): Plugin {\n let config: ResolvedConfig;\n let handler: CopyAssetsHandler;\n let dispose: () => void;\n\n if (global.NX_GRAPH_CREATION) return;\n\n return {\n name: 'nx-copy-assets-plugin',\n configResolved(_config) {\n config = _config;\n },\n async buildStart() {\n const relativeProjectRoot = relative(workspaceRoot, config.root);\n const assets = _assets.map((a) => {\n if (typeof a === 'string') {\n return joinPathFragments(relativeProjectRoot, a);\n } else {\n return {\n ...a,\n input: joinPathFragments(relativeProjectRoot, a.input),\n };\n }\n });\n handler = new CopyAssetsHandler({\n rootDir: workspaceRoot,\n projectDir: config.root,\n outputDir: config.build.outDir.startsWith(config.root)\n ? config.build.outDir\n : join(config.root, config.build.outDir),\n assets,\n });\n if (this.meta.watchMode && isDaemonEnabled()) {\n dispose = await handler.watchAndProcessOnAssetChange();\n }\n },\n async writeBundle() {\n await handler.processAllAssetsOnce();\n },\n async closeWatcher() {\n dispose == null ? void 0 : dispose();\n },\n };\n}\n"],"names":["nxCopyAssetsPlugin","_assets","config","handler","dispose","global","NX_GRAPH_CREATION","name","configResolved","_config","buildStart","relativeProjectRoot","relative","workspaceRoot","root","assets","map","a","joinPathFragments","input","CopyAssetsHandler","rootDir","projectDir","outputDir","build","outDir","startsWith","join","meta","watchMode","isDaemonEnabled","watchAndProcessOnAssetChange","writeBundle","processAllAssetsOnce","closeWatcher"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BAMgBA;;;eAAAA;;;;0BANe;wBAEmC;mCAEhC;AAE3B,SAASA,mBAAmBC,OAA+B;IAChE,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,IAAIC,OAAOC,iBAAiB,EAAE;IAE9B,OAAO;QACLC,MAAM;QACNC,gBAAeC,OAAO;YACpBP,SAASO;QACX;QACA,MAAMC;YACJ,MAAMC,sBAAsBC,IAAAA,kBAAQ,EAACC,qBAAa,EAAEX,OAAOY,IAAI;YAC/D,MAAMC,SAASd,QAAQe,GAAG,CAAC,CAACC;gBAC1B,IAAI,OAAOA,MAAM,UAAU;oBACzB,OAAOC,IAAAA,yBAAiB,EAACP,qBAAqBM;gBAChD,OAAO;oBACL,OAAO,eACFA;wBACHE,OAAOD,IAAAA,yBAAiB,EAACP,qBAAqBM,EAAEE,KAAK;;gBAEzD;YACF;YACAhB,UAAU,IAAIiB,oCAAiB,CAAC;gBAC9BC,SAASR,qBAAa;gBACtBS,YAAYpB,OAAOY,IAAI;gBACvBS,WAAWrB,OAAOsB,KAAK,CAACC,MAAM,CAACC,UAAU,CAACxB,OAAOY,IAAI,IACjDZ,OAAOsB,KAAK,CAACC,MAAM,GACnBE,IAAAA,cAAI,EAACzB,OAAOY,IAAI,EAAEZ,OAAOsB,KAAK,CAACC,MAAM;gBACzCV;YACF;YACA,IAAI,IAAI,CAACa,IAAI,CAACC,SAAS,IAAIC,IAAAA,uBAAe,KAAI;gBAC5C1B,UAAU,MAAMD,QAAQ4B,4BAA4B;YACtD;QACF;QACA,MAAMC;YACJ,MAAM7B,QAAQ8B,oBAAoB;QACpC;QACA,MAAMC;YACJ9B,WAAW,OAAO,KAAK,IAAIA;QAC7B;IACF;AACF"}
|
|
@@ -2,7 +2,8 @@ import { Plugin } from 'vite';
|
|
|
2
2
|
export interface nxViteTsPathsOptions {
|
|
3
3
|
/**
|
|
4
4
|
* Enable debug logging
|
|
5
|
-
*
|
|
5
|
+
* If set to false, it will always ignore the debug logging even when `--verbose` or `NX_VERBOSE_LOGGING` is set to true.
|
|
6
|
+
* @default undefined
|
|
6
7
|
**/
|
|
7
8
|
debug?: boolean;
|
|
8
9
|
/**
|
|
@@ -15,6 +15,7 @@ const _nxtsconfigpathsfindfile = require("../src/utils/nx-tsconfig-paths-find-fi
|
|
|
15
15
|
const _tssolutionsetup = require("@nx/js/src/utils/typescript/ts-solution-setup");
|
|
16
16
|
function nxViteTsPaths(options = {}) {
|
|
17
17
|
var _options, _options1, _options2;
|
|
18
|
+
let foundTsConfigPath;
|
|
18
19
|
let matchTsPathEsm;
|
|
19
20
|
let matchTsPathFallback;
|
|
20
21
|
let tsConfigPathsEsm;
|
|
@@ -55,12 +56,9 @@ function nxViteTsPaths(options = {}) {
|
|
|
55
56
|
async configResolved (config) {
|
|
56
57
|
projectRoot = config.root;
|
|
57
58
|
const projectRootFromWorkspaceRoot = (0, _nodepath.relative)(_devkit.workspaceRoot, projectRoot);
|
|
58
|
-
var _process_env_NX_TASK_TARGET_TARGET;
|
|
59
|
-
|
|
60
|
-
if (!foundTsConfigPath)
|
|
61
|
-
throw new Error((0, _devkit.stripIndents)`Unable to find a tsconfig in the workspace!
|
|
62
|
-
There should at least be a tsconfig.base.json or tsconfig.json in the root of the workspace ${_devkit.workspaceRoot}`);
|
|
63
|
-
}
|
|
59
|
+
var _process_env_NX_TASK_TARGET_TARGET, _process_env_NX_TSCONFIG_PATH;
|
|
60
|
+
foundTsConfigPath = getTsConfig((_process_env_NX_TSCONFIG_PATH = process.env.NX_TSCONFIG_PATH) != null ? _process_env_NX_TSCONFIG_PATH : (0, _nodepath.join)(_devkit.workspaceRoot, 'tmp', projectRootFromWorkspaceRoot, (_process_env_NX_TASK_TARGET_TARGET = process.env.NX_TASK_TARGET_TARGET) != null ? _process_env_NX_TASK_TARGET_TARGET : 'build', 'tsconfig.generated.json'));
|
|
61
|
+
if (!foundTsConfigPath) return;
|
|
64
62
|
if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION && config.mode !== 'test') {
|
|
65
63
|
const projectGraph = await (0, _devkit.createProjectGraphAsync)({
|
|
66
64
|
exitOnError: false,
|
|
@@ -99,6 +97,8 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
|
|
|
99
97
|
}
|
|
100
98
|
},
|
|
101
99
|
resolveId (importPath) {
|
|
100
|
+
// Let other resolvers handle this path.
|
|
101
|
+
if (!foundTsConfigPath) return null;
|
|
102
102
|
let resolvedFile;
|
|
103
103
|
try {
|
|
104
104
|
resolvedFile = matchTsPathEsm(importPath);
|
|
@@ -137,7 +137,8 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
|
|
|
137
137
|
return [
|
|
138
138
|
(0, _nodepath.resolve)(preferredTsConfigPath),
|
|
139
139
|
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.base.json')),
|
|
140
|
-
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.json'))
|
|
140
|
+
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.json')),
|
|
141
|
+
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'jsconfig.json'))
|
|
141
142
|
].find((tsPath)=>{
|
|
142
143
|
if ((0, _nodefs.existsSync)(tsPath)) {
|
|
143
144
|
logIt('Found tsconfig at', tsPath);
|
|
@@ -146,7 +147,7 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
|
|
|
146
147
|
});
|
|
147
148
|
}
|
|
148
149
|
function logIt(...msg) {
|
|
149
|
-
if (process.env.NX_VERBOSE_LOGGING === 'true'
|
|
150
|
+
if (process.env.NX_VERBOSE_LOGGING === 'true' && (options == null ? void 0 : options.debug) !== false) {
|
|
150
151
|
console.debug('\n[Nx Vite TsPaths]', ...msg);
|
|
151
152
|
}
|
|
152
153
|
}
|
|
@@ -159,6 +160,11 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th
|
|
|
159
160
|
if (importPath === normalizedImport || importPath.startsWith(normalizedImport + '/')) {
|
|
160
161
|
const joinedPath = (0, _devkit.joinPathFragments)(tsconfig.absoluteBaseUrl, paths[0].replace(/\/\*$/, ''));
|
|
161
162
|
resolvedFile = (0, _nxtsconfigpathsfindfile.findFile)(importPath.replace(normalizedImport, joinedPath), options.extensions);
|
|
163
|
+
if (resolvedFile === undefined && options.extensions.some((ext)=>importPath.endsWith(ext))) {
|
|
164
|
+
const foundExtension = options.extensions.find((ext)=>importPath.endsWith(ext));
|
|
165
|
+
const pathWithoutExtension = importPath.replace(normalizedImport, joinedPath).slice(0, -foundExtension.length);
|
|
166
|
+
resolvedFile = (0, _nxtsconfigpathsfindfile.findFile)(pathWithoutExtension, options.extensions);
|
|
167
|
+
}
|
|
162
168
|
}
|
|
163
169
|
}
|
|
164
170
|
return resolvedFile;
|
|
@@ -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 { join, relative, 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';\nimport { findFile } from '../src/utils/nx-tsconfig-paths-find-file';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\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 '.mts',\n '.mjs',\n '.cts',\n '.cjs',\n '.css',\n '.scss',\n '.less',\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 // Ensure the resolveId aspect of the plugin is called before vite's internal resolver\n // Otherwise, issues can arise with Yarn Workspaces and Pnpm Workspaces\n enforce: 'pre',\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 || !existsSync(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 if (isUsingTsSolutionSetup()) return;\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 (\n importPath === normalizedImport ||\n importPath.startsWith(normalizedImport + '/')\n ) {\n const joinedPath = joinPathFragments(\n tsconfig.absoluteBaseUrl,\n paths[0].replace(/\\/\\*$/, '')\n );\n\n resolvedFile = findFile(\n importPath.replace(normalizedImport, joinedPath),\n options.extensions\n );\n }\n }\n\n return resolvedFile;\n }\n}\n"],"names":["nxViteTsPaths","options","matchTsPathEsm","matchTsPathFallback","tsConfigPathsEsm","tsConfigPathsFallback","extensions","mainFields","buildLibsFromSource","projectRoot","name","enforce","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","existsSync","loadFileFromPaths","writeBundle","isUsingTsSolutionSetup","outDir","dir","src","resolve","dest","copyFileSync","err","console","error","preferredTsConfigPath","find","tsPath","msg","NX_VERBOSE_LOGGING","debug","tsconfig","configFileAbsolutePath","alias","normalizedImport","replace","startsWith","joinedPath","joinPathFragments","findFile"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BAiDgBA;;;eAAAA;;;wBA5CT;wBACkC;0BACD;+BAMjC;oCAIA;+CAEuC;yCACrB;iCACc;AA4BhC,SAASA,cAAcC,UAAgC,CAAC,CAAC;QAM9DA,UAcAA,WACAA;IApBA,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;;IAEJJ,gBAAAA,WAAAA,SAAQK,oCAARL,SAAQK,aAAe;QACrB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD;;IACDL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BACPkB,QAAmC,EACnCtB,UAAkB;QAElBR,MACE,CAAC,sCAAsC,EAAE8B,SAASC,sBAAsB,CAAC,CAAC;QAE5E,IAAItB;QACJ,IAAK,MAAMuB,SAASF,SAAS1B,KAAK,CAAE;YAClC,MAAMA,QAAQ0B,SAAS1B,KAAK,CAAC4B,MAAM;YAEnC,MAAMC,mBAAmBD,MAAME,OAAO,CAAC,SAAS;YAEhD,IACE1B,eAAeyB,oBACfzB,WAAW2B,UAAU,CAACF,mBAAmB,MACzC;gBACA,MAAMG,aAAaC,IAAAA,yBAAiB,EAClCP,SAAS3B,eAAe,EACxBC,KAAK,CAAC,EAAE,CAAC8B,OAAO,CAAC,SAAS;gBAG5BzB,eAAe6B,IAAAA,iCAAQ,EACrB9B,WAAW0B,OAAO,CAACD,kBAAkBG,aACrCvF,QAAQK,UAAU;YAEtB;QACF;QAEA,OAAOuD;IACT;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 { join, relative, 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';\nimport { findFile } from '../src/utils/nx-tsconfig-paths-find-file';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport interface nxViteTsPathsOptions {\n /**\n * Enable debug logging\n * If set to false, it will always ignore the debug logging even when `--verbose` or `NX_VERBOSE_LOGGING` is set to true.\n * @default undefined\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 foundTsConfigPath: string;\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 '.mts',\n '.mjs',\n '.cts',\n '.cjs',\n '.css',\n '.scss',\n '.less',\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 // Ensure the resolveId aspect of the plugin is called before vite's internal resolver\n // Otherwise, issues can arise with Yarn Workspaces and Pnpm Workspaces\n enforce: 'pre',\n async configResolved(config: any) {\n projectRoot = config.root;\n const projectRootFromWorkspaceRoot = relative(workspaceRoot, projectRoot);\n foundTsConfigPath = getTsConfig(\n process.env.NX_TSCONFIG_PATH ??\n join(\n workspaceRoot,\n 'tmp',\n projectRootFromWorkspaceRoot,\n process.env.NX_TASK_TARGET_TARGET ?? 'build',\n 'tsconfig.generated.json'\n )\n );\n\n if (!foundTsConfigPath) return;\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 other resolvers handle this path.\n if (!foundTsConfigPath) return null;\n\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 || !existsSync(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 if (isUsingTsSolutionSetup()) return;\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 resolve(join(workspaceRoot, 'jsconfig.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 !== false) {\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 (\n importPath === normalizedImport ||\n importPath.startsWith(normalizedImport + '/')\n ) {\n const joinedPath = joinPathFragments(\n tsconfig.absoluteBaseUrl,\n paths[0].replace(/\\/\\*$/, '')\n );\n\n resolvedFile = findFile(\n importPath.replace(normalizedImport, joinedPath),\n options.extensions\n );\n\n if (\n resolvedFile === undefined &&\n options.extensions.some((ext) => importPath.endsWith(ext))\n ) {\n const foundExtension = options.extensions.find((ext) =>\n importPath.endsWith(ext)\n );\n const pathWithoutExtension = importPath\n .replace(normalizedImport, joinedPath)\n .slice(0, -foundExtension.length);\n resolvedFile = findFile(pathWithoutExtension, options.extensions);\n }\n }\n }\n\n return resolvedFile;\n }\n}\n"],"names":["nxViteTsPaths","options","foundTsConfigPath","matchTsPathEsm","matchTsPathFallback","tsConfigPathsEsm","tsConfigPathsFallback","extensions","mainFields","buildLibsFromSource","projectRoot","name","enforce","configResolved","config","root","projectRootFromWorkspaceRoot","relative","workspaceRoot","process","getTsConfig","env","NX_TSCONFIG_PATH","join","NX_TASK_TARGET_TARGET","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","Error","createMatchPath","absoluteBaseUrl","paths","rootLevelTsConfig","rootLevelParsed","resolveId","importPath","resolvedFile","e","existsSync","loadFileFromPaths","writeBundle","isUsingTsSolutionSetup","outDir","dir","src","resolve","dest","copyFileSync","err","console","error","preferredTsConfigPath","find","tsPath","msg","NX_VERBOSE_LOGGING","debug","tsconfig","configFileAbsolutePath","alias","normalizedImport","replace","startsWith","joinedPath","joinPathFragments","findFile","some","ext","endsWith","foundExtension","pathWithoutExtension","slice","length"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,kBAAkBG,YAC1BQ,KAAK,CAAC,GAAG,CAACF,eAAeG,MAAM;oBAClCpC,eAAe6B,IAAAA,iCAAQ,EAACK,sBAAsB9F,QAAQM,UAAU;gBAClE;YACF;QACF;QAEA,OAAOsD;IACT;AACF"}
|
|
@@ -2,10 +2,8 @@ import { ExecutorContext } from '@nx/devkit';
|
|
|
2
2
|
import { ViteBuildExecutorOptions } from './schema';
|
|
3
3
|
export declare function viteBuildExecutor(options: Record<string, any> & ViteBuildExecutorOptions, context: ExecutorContext): AsyncGenerator<{
|
|
4
4
|
success: boolean;
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
outfile: string;
|
|
8
|
-
}, void, any>;
|
|
5
|
+
outfile?: string;
|
|
6
|
+
}, any, any>;
|
|
9
7
|
export declare function getBuildExtraArgs(options: ViteBuildExecutorOptions): Promise<{
|
|
10
8
|
buildOptions: Record<string, unknown>;
|
|
11
9
|
otherOptions: Record<string, any>;
|
|
@@ -29,11 +29,11 @@ async function* viteBuildExecutor(options, context) {
|
|
|
29
29
|
var _resolved_build;
|
|
30
30
|
process.env.VITE_CJS_IGNORE_WARNING = 'true';
|
|
31
31
|
// Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
|
|
32
|
-
const { mergeConfig, build, resolveConfig } = await (0, _executorutils.loadViteDynamicImport)();
|
|
32
|
+
const { mergeConfig, build, resolveConfig, createBuilder } = await (0, _executorutils.loadViteDynamicImport)();
|
|
33
33
|
const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
|
|
34
34
|
const tsConfigForBuild = (0, _executorutils.createBuildableTsConfig)(projectRoot, options, context);
|
|
35
35
|
const viteConfigPath = (0, _optionsutils.normalizeViteConfigFilePath)(context.root, projectRoot, options.configFile);
|
|
36
|
-
const root = projectRoot === '.' ? process.cwd() : (0, _path.relative)(context.cwd, (0, _devkit.joinPathFragments)(context.root, projectRoot));
|
|
36
|
+
const root = projectRoot === '.' || projectRoot === '' ? process.cwd() : (0, _path.relative)(context.cwd, (0, _devkit.joinPathFragments)(context.root, projectRoot));
|
|
37
37
|
const { buildOptions, otherOptions } = await getBuildExtraArgs(options);
|
|
38
38
|
var _otherOptions_mode;
|
|
39
39
|
const defaultMode = (_otherOptions_mode = otherOptions == null ? void 0 : otherOptions.mode) != null ? _otherOptions_mode : 'production';
|
|
@@ -64,78 +64,94 @@ async function* viteBuildExecutor(options, context) {
|
|
|
64
64
|
isVueProject: Boolean((_resolved_plugins = resolved.plugins) == null ? void 0 : _resolved_plugins.find((plugin)=>typeof plugin === 'object' && (plugin == null ? void 0 : plugin.name) === 'vite:vue'))
|
|
65
65
|
});
|
|
66
66
|
}
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
// So, we calculate the relative path from the workspace root to the outdir.
|
|
72
|
-
const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');
|
|
73
|
-
const distPackageJson = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, 'package.json');
|
|
74
|
-
// Generate a package.json if option has been set.
|
|
75
|
-
if (options.generatePackageJson) {
|
|
76
|
-
var _builtPackageJson;
|
|
77
|
-
if (context.projectGraph.nodes[context.projectName].type !== 'app') {
|
|
78
|
-
_devkit.logger.warn((0, _devkit.stripIndents)`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.
|
|
79
|
-
For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`);
|
|
67
|
+
const builder = createBuilder !== undefined && options.useEnvironmentsApi ? await createBuilder(buildConfig) : {
|
|
68
|
+
build: (inlineConfig)=>build(inlineConfig),
|
|
69
|
+
environments: {
|
|
70
|
+
build: buildConfig
|
|
80
71
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
(0,
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
{
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
const iterable = (0, _asynciterable.createAsyncIterable)(({ next })=>{
|
|
110
|
-
let success = true;
|
|
111
|
-
watcherOrOutput.on('event', (event)=>{
|
|
112
|
-
if (event.code === 'START') {
|
|
113
|
-
success = true;
|
|
114
|
-
} else if (event.code === 'ERROR') {
|
|
115
|
-
success = false;
|
|
116
|
-
} else if (event.code === 'END') {
|
|
117
|
-
next({
|
|
118
|
-
success
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
// result must be closed when present.
|
|
122
|
-
// see https://rollupjs.org/guide/en/#rollupwatch
|
|
123
|
-
if ('result' in event && event.result) {
|
|
124
|
-
event.result.close();
|
|
125
|
-
}
|
|
72
|
+
};
|
|
73
|
+
let iterables = [];
|
|
74
|
+
for (const env of Object.values(builder.environments)){
|
|
75
|
+
var _env_config;
|
|
76
|
+
// This is needed to overwrite the resolve build config with executor options in Vite 6
|
|
77
|
+
if ((_env_config = env.config) == null ? void 0 : _env_config.build) {
|
|
78
|
+
env.config.build = _extends._({}, env.config.build, buildConfig.build);
|
|
79
|
+
}
|
|
80
|
+
const watcherOrOutput = await builder.build(env);
|
|
81
|
+
const libraryPackageJson = (0, _path.resolve)(projectRoot, 'package.json');
|
|
82
|
+
const rootPackageJson = (0, _path.resolve)(context.root, 'package.json');
|
|
83
|
+
// Here, we want the outdir relative to the workspace root.
|
|
84
|
+
// So, we calculate the relative path from the workspace root to the outdir.
|
|
85
|
+
const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');
|
|
86
|
+
const distPackageJson = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, 'package.json');
|
|
87
|
+
// Generate a package.json if option has been set.
|
|
88
|
+
if (options.generatePackageJson) {
|
|
89
|
+
var _builtPackageJson;
|
|
90
|
+
if (context.projectGraph.nodes[context.projectName].type !== 'app') {
|
|
91
|
+
_devkit.logger.warn((0, _devkit.stripIndents)`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.
|
|
92
|
+
For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`);
|
|
93
|
+
}
|
|
94
|
+
const builtPackageJson = (0, _js.createPackageJson)(context.projectName, context.projectGraph, {
|
|
95
|
+
target: context.targetName,
|
|
96
|
+
root: context.root,
|
|
97
|
+
isProduction: !options.includeDevDependenciesInPackageJson,
|
|
98
|
+
skipOverrides: options.skipOverrides,
|
|
99
|
+
skipPackageManager: options.skipPackageManager
|
|
126
100
|
});
|
|
101
|
+
var _type;
|
|
102
|
+
(_type = (_builtPackageJson = builtPackageJson).type) != null ? _type : _builtPackageJson.type = 'module';
|
|
103
|
+
(0, _devkit.writeJsonFile)(`${outDirRelativeToWorkspaceRoot}/package.json`, builtPackageJson);
|
|
104
|
+
const packageManager = (0, _devkit.detectPackageManager)(context.root);
|
|
105
|
+
const lockFile = (0, _js.createLockFile)(builtPackageJson, context.projectGraph, packageManager);
|
|
106
|
+
(0, _fs.writeFileSync)(`${outDirRelativeToWorkspaceRoot}/${(0, _js.getLockFileName)(packageManager)}`, lockFile, {
|
|
107
|
+
encoding: 'utf-8'
|
|
108
|
+
});
|
|
109
|
+
} else if (options.generatePackageJson !== false && !(0, _fs.existsSync)(distPackageJson) && (0, _fs.existsSync)(libraryPackageJson) && rootPackageJson !== libraryPackageJson) {
|
|
110
|
+
await (0, _js.copyAssets)({
|
|
111
|
+
outputPath: outDirRelativeToWorkspaceRoot,
|
|
112
|
+
assets: [
|
|
113
|
+
{
|
|
114
|
+
input: projectRoot,
|
|
115
|
+
output: '.',
|
|
116
|
+
glob: 'package.json'
|
|
117
|
+
}
|
|
118
|
+
]
|
|
119
|
+
}, context);
|
|
120
|
+
}
|
|
121
|
+
const iterable = (0, _asynciterable.createAsyncIterable)(({ next, done })=>{
|
|
122
|
+
if ('on' in watcherOrOutput) {
|
|
123
|
+
let success = true;
|
|
124
|
+
watcherOrOutput.on('event', (event)=>{
|
|
125
|
+
if (event.code === 'START') {
|
|
126
|
+
success = true;
|
|
127
|
+
} else if (event.code === 'ERROR') {
|
|
128
|
+
success = false;
|
|
129
|
+
} else if (event.code === 'END') {
|
|
130
|
+
next({
|
|
131
|
+
success
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// result must be closed when present.
|
|
135
|
+
// see https://rollupjs.org/guide/en/#rollupwatch
|
|
136
|
+
if ('result' in event && event.result) {
|
|
137
|
+
event.result.close();
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
} else {
|
|
141
|
+
var _watcherOrOutput_, _output_;
|
|
142
|
+
const output = (watcherOrOutput == null ? void 0 : watcherOrOutput['output']) || (watcherOrOutput == null ? void 0 : (_watcherOrOutput_ = watcherOrOutput[0]) == null ? void 0 : _watcherOrOutput_.output);
|
|
143
|
+
const fileName = (output == null ? void 0 : (_output_ = output[0]) == null ? void 0 : _output_.fileName) || 'main.cjs';
|
|
144
|
+
const outfile = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, fileName);
|
|
145
|
+
next({
|
|
146
|
+
success: true,
|
|
147
|
+
outfile
|
|
148
|
+
});
|
|
149
|
+
done();
|
|
150
|
+
}
|
|
127
151
|
});
|
|
128
|
-
|
|
129
|
-
} else {
|
|
130
|
-
var _watcherOrOutput_, _output_;
|
|
131
|
-
const output = (watcherOrOutput == null ? void 0 : watcherOrOutput['output']) || (watcherOrOutput == null ? void 0 : (_watcherOrOutput_ = watcherOrOutput[0]) == null ? void 0 : _watcherOrOutput_.output);
|
|
132
|
-
const fileName = (output == null ? void 0 : (_output_ = output[0]) == null ? void 0 : _output_.fileName) || 'main.cjs';
|
|
133
|
-
const outfile = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, fileName);
|
|
134
|
-
yield {
|
|
135
|
-
success: true,
|
|
136
|
-
outfile
|
|
137
|
-
};
|
|
152
|
+
iterables.push(iterable);
|
|
138
153
|
}
|
|
154
|
+
return yield* (0, _asynciterable.combineAsyncIterables)(iterables.shift(), ...iterables != null ? iterables : []);
|
|
139
155
|
}
|
|
140
156
|
async function getBuildExtraArgs(options) {
|
|
141
157
|
// support passing extra args to vite cli
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/vite/src/executors/build/build.impl.ts"],"sourcesContent":["import {\n detectPackageManager,\n ExecutorContext,\n joinPathFragments,\n logger,\n offsetFromRoot,\n stripIndents,\n writeJsonFile,\n} from '@nx/devkit';\nimport {\n getProjectTsConfigPath,\n normalizeViteConfigFilePath,\n} from '../../utils/options-utils';\nimport { ViteBuildExecutorOptions } from './schema';\nimport {\n copyAssets,\n createLockFile,\n createPackageJson,\n getLockFileName,\n} from '@nx/js';\nimport { existsSync, writeFileSync } from 'fs';\nimport { relative, resolve } from 'path';\nimport { createAsyncIterable } from '@nx/devkit/src/utils/async-iterable';\nimport {\n createBuildableTsConfig,\n loadViteDynamicImport,\n validateTypes,\n} from '../../utils/executor-utils';\nimport { type Plugin } from 'vite';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport async function* viteBuildExecutor(\n options: Record<string, any> & ViteBuildExecutorOptions,\n context: ExecutorContext\n) {\n process.env.VITE_CJS_IGNORE_WARNING = 'true';\n // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.\n const { mergeConfig, build, resolveConfig } = await loadViteDynamicImport();\n const projectRoot =\n context.projectsConfigurations.projects[context.projectName].root;\n const tsConfigForBuild = createBuildableTsConfig(\n projectRoot,\n options,\n context\n );\n\n const viteConfigPath = normalizeViteConfigFilePath(\n context.root,\n projectRoot,\n options.configFile\n );\n const root =\n projectRoot === '.'\n ? process.cwd()\n : relative(context.cwd, joinPathFragments(context.root, projectRoot));\n\n const { buildOptions, otherOptions } = await getBuildExtraArgs(options);\n const defaultMode = otherOptions?.mode ?? 'production';\n\n const resolved = await resolveConfig(\n {\n configFile: viteConfigPath,\n mode: defaultMode,\n },\n 'build',\n defaultMode,\n process.env.NODE_ENV ?? defaultMode\n );\n\n const outDir =\n joinPathFragments(offsetFromRoot(projectRoot), options.outputPath) ??\n resolved?.build?.outDir;\n\n const buildConfig = mergeConfig(\n {\n // This should not be needed as it's going to be set in vite.config.ts\n // but leaving it here in case someone did not migrate correctly\n root: resolved.root ?? root,\n configFile: viteConfigPath,\n },\n {\n build: {\n outDir,\n ...buildOptions,\n },\n ...otherOptions,\n }\n );\n // New TS Solution already has a typecheck target\n if (!options.skipTypeCheck && !isUsingTsSolutionSetup()) {\n await validateTypes({\n workspaceRoot: context.root,\n tsconfig: tsConfigForBuild,\n isVueProject: Boolean(\n resolved.plugins?.find(\n (plugin: Plugin) =>\n typeof plugin === 'object' && plugin?.name === 'vite:vue'\n )\n ),\n });\n }\n\n const watcherOrOutput = await build(buildConfig);\n\n const libraryPackageJson = resolve(projectRoot, 'package.json');\n const rootPackageJson = resolve(context.root, 'package.json');\n\n // Here, we want the outdir relative to the workspace root.\n // So, we calculate the relative path from the workspace root to the outdir.\n const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');\n const distPackageJson = resolve(\n outDirRelativeToWorkspaceRoot,\n 'package.json'\n );\n\n // Generate a package.json if option has been set.\n if (options.generatePackageJson) {\n if (context.projectGraph.nodes[context.projectName].type !== 'app') {\n logger.warn(\n stripIndents`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.\n For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`\n );\n }\n\n const builtPackageJson = createPackageJson(\n context.projectName,\n context.projectGraph,\n {\n target: context.targetName,\n root: context.root,\n isProduction: !options.includeDevDependenciesInPackageJson, // By default we remove devDependencies since this is a production build.\n skipOverrides: options.skipOverrides,\n skipPackageManager: options.skipPackageManager,\n }\n );\n\n builtPackageJson.type ??= 'module';\n\n writeJsonFile(\n `${outDirRelativeToWorkspaceRoot}/package.json`,\n builtPackageJson\n );\n const packageManager = detectPackageManager(context.root);\n\n const lockFile = createLockFile(\n builtPackageJson,\n context.projectGraph,\n packageManager\n );\n writeFileSync(\n `${outDirRelativeToWorkspaceRoot}/${getLockFileName(packageManager)}`,\n lockFile,\n {\n encoding: 'utf-8',\n }\n );\n }\n // For buildable libs, copy package.json if it exists.\n else if (\n options.generatePackageJson !== false &&\n !existsSync(distPackageJson) &&\n existsSync(libraryPackageJson) &&\n rootPackageJson !== libraryPackageJson\n ) {\n await copyAssets(\n {\n outputPath: outDirRelativeToWorkspaceRoot,\n assets: [\n {\n input: projectRoot,\n output: '.',\n glob: 'package.json',\n },\n ],\n },\n context\n );\n }\n\n if ('on' in watcherOrOutput) {\n const iterable = createAsyncIterable<{ success: boolean }>(({ next }) => {\n let success = true;\n watcherOrOutput.on('event', (event) => {\n if (event.code === 'START') {\n success = true;\n } else if (event.code === 'ERROR') {\n success = false;\n } else if (event.code === 'END') {\n next({ success });\n }\n // result must be closed when present.\n // see https://rollupjs.org/guide/en/#rollupwatch\n if ('result' in event && event.result) {\n event.result.close();\n }\n });\n });\n yield* iterable;\n } else {\n const output = watcherOrOutput?.['output'] || watcherOrOutput?.[0]?.output;\n const fileName = output?.[0]?.fileName || 'main.cjs';\n const outfile = resolve(outDirRelativeToWorkspaceRoot, fileName);\n yield { success: true, outfile };\n }\n}\n\nexport async function getBuildExtraArgs(\n options: ViteBuildExecutorOptions\n): Promise<{\n // vite BuildOptions\n buildOptions: Record<string, unknown>;\n otherOptions: Record<string, any>;\n}> {\n // support passing extra args to vite cli\n const schema = await import('./schema.json');\n const extraArgs = {};\n for (const key of Object.keys(options)) {\n if (!schema.properties[key]) {\n extraArgs[key] = options[key];\n }\n }\n\n const buildOptions = {};\n const buildSchemaKeys = [\n 'target',\n 'polyfillModulePreload',\n 'modulePreload',\n 'outDir',\n 'assetsDir',\n 'assetsInlineLimit',\n 'cssCodeSplit',\n 'cssTarget',\n 'cssMinify',\n 'sourcemap',\n 'minify',\n 'terserOptions',\n 'rollupOptions',\n 'commonjsOptions',\n 'dynamicImportVarsOptions',\n 'write',\n 'emptyOutDir',\n 'copyPublicDir',\n 'manifest',\n 'lib',\n 'ssr',\n 'ssrManifest',\n 'ssrEmitAssets',\n 'reportCompressedSize',\n 'chunkSizeWarningLimit',\n 'watch',\n ];\n const otherOptions = {};\n for (const key of Object.keys(extraArgs)) {\n if (buildSchemaKeys.includes(key)) {\n buildOptions[key] = extraArgs[key];\n } else {\n otherOptions[key] = extraArgs[key];\n }\n }\n\n buildOptions['watch'] = options.watch ?? undefined;\n\n return {\n buildOptions,\n otherOptions,\n };\n}\n\nexport default viteBuildExecutor;\n"],"names":["getBuildExtraArgs","viteBuildExecutor","options","context","resolved","process","env","VITE_CJS_IGNORE_WARNING","mergeConfig","build","resolveConfig","loadViteDynamicImport","projectRoot","projectsConfigurations","projects","projectName","root","tsConfigForBuild","createBuildableTsConfig","viteConfigPath","normalizeViteConfigFilePath","configFile","cwd","relative","joinPathFragments","buildOptions","otherOptions","defaultMode","mode","NODE_ENV","outDir","offsetFromRoot","outputPath","buildConfig","skipTypeCheck","isUsingTsSolutionSetup","validateTypes","workspaceRoot","tsconfig","isVueProject","Boolean","plugins","find","plugin","name","watcherOrOutput","libraryPackageJson","resolve","rootPackageJson","outDirRelativeToWorkspaceRoot","replaceAll","distPackageJson","generatePackageJson","builtPackageJson","projectGraph","nodes","type","logger","warn","stripIndents","createPackageJson","target","targetName","isProduction","includeDevDependenciesInPackageJson","skipOverrides","skipPackageManager","writeJsonFile","packageManager","detectPackageManager","lockFile","createLockFile","writeFileSync","getLockFileName","encoding","existsSync","copyAssets","assets","input","output","glob","iterable","createAsyncIterable","next","success","on","event","code","result","close","fileName","outfile","schema","extraArgs","key","Object","keys","properties","bu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YAAY,CAACqE,IAAI,GAAGD,SAAS,CAACC,IAAI;QACpC,OAAO;YACLpE,YAAY,CAACoE,IAAI,GAAGD,SAAS,CAACC,IAAI;QACpC;IACF;QAEwB5F;IAAxBuB,YAAY,CAAC,QAAQ,GAAGvB,CAAAA,iBAAAA,QAAQkG,KAAK,YAAblG,iBAAiBmG;IAEzC,OAAO;QACL5E;QACAC;IACF;AACF;MAEA,WAAezB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/vite/src/executors/build/build.impl.ts"],"sourcesContent":["import {\n detectPackageManager,\n ExecutorContext,\n joinPathFragments,\n logger,\n offsetFromRoot,\n stripIndents,\n writeJsonFile,\n} from '@nx/devkit';\nimport {\n getProjectTsConfigPath,\n normalizeViteConfigFilePath,\n} from '../../utils/options-utils';\nimport { ViteBuildExecutorOptions } from './schema';\nimport {\n copyAssets,\n createLockFile,\n createPackageJson,\n getLockFileName,\n} from '@nx/js';\nimport { existsSync, writeFileSync } from 'fs';\nimport { relative, resolve } from 'path';\nimport {\n combineAsyncIterables,\n createAsyncIterable,\n} from '@nx/devkit/src/utils/async-iterable';\nimport {\n createBuildableTsConfig,\n loadViteDynamicImport,\n validateTypes,\n} from '../../utils/executor-utils';\nimport { type Plugin } from 'vite';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport async function* viteBuildExecutor(\n options: Record<string, any> & ViteBuildExecutorOptions,\n context: ExecutorContext\n) {\n process.env.VITE_CJS_IGNORE_WARNING = 'true';\n // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.\n const { mergeConfig, build, resolveConfig, createBuilder } =\n await loadViteDynamicImport();\n const projectRoot =\n context.projectsConfigurations.projects[context.projectName].root;\n const tsConfigForBuild = createBuildableTsConfig(\n projectRoot,\n options,\n context\n );\n\n const viteConfigPath = normalizeViteConfigFilePath(\n context.root,\n projectRoot,\n options.configFile\n );\n const root =\n projectRoot === '.' || projectRoot === ''\n ? process.cwd()\n : relative(context.cwd, joinPathFragments(context.root, projectRoot));\n\n const { buildOptions, otherOptions } = await getBuildExtraArgs(options);\n const defaultMode = otherOptions?.mode ?? 'production';\n\n const resolved = await resolveConfig(\n {\n configFile: viteConfigPath,\n mode: defaultMode,\n },\n 'build',\n defaultMode,\n process.env.NODE_ENV ?? defaultMode\n );\n\n const outDir =\n joinPathFragments(offsetFromRoot(projectRoot), options.outputPath) ??\n resolved?.build?.outDir;\n\n const buildConfig = mergeConfig(\n {\n // This should not be needed as it's going to be set in vite.config.ts\n // but leaving it here in case someone did not migrate correctly\n root: resolved.root ?? root,\n configFile: viteConfigPath,\n },\n {\n build: {\n outDir,\n ...buildOptions,\n },\n ...otherOptions,\n }\n );\n // New TS Solution already has a typecheck target\n if (!options.skipTypeCheck && !isUsingTsSolutionSetup()) {\n await validateTypes({\n workspaceRoot: context.root,\n tsconfig: tsConfigForBuild,\n isVueProject: Boolean(\n resolved.plugins?.find(\n (plugin: Plugin) =>\n typeof plugin === 'object' && plugin?.name === 'vite:vue'\n )\n ),\n });\n }\n\n const builder =\n createBuilder !== undefined && options.useEnvironmentsApi\n ? await createBuilder(buildConfig)\n : // This is needed to ensure support for Vite 5\n {\n build: (inlineConfig) => build(inlineConfig),\n environments: { build: buildConfig },\n };\n\n let iterables: AsyncIterable<{ success: boolean; outfile?: string }>[] = [];\n for (const env of Object.values(builder.environments)) {\n // This is needed to overwrite the resolve build config with executor options in Vite 6\n if (env.config?.build) {\n env.config.build = {\n ...env.config.build,\n ...buildConfig.build,\n };\n }\n const watcherOrOutput = await builder.build(env as any);\n\n const libraryPackageJson = resolve(projectRoot, 'package.json');\n const rootPackageJson = resolve(context.root, 'package.json');\n\n // Here, we want the outdir relative to the workspace root.\n // So, we calculate the relative path from the workspace root to the outdir.\n const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');\n const distPackageJson = resolve(\n outDirRelativeToWorkspaceRoot,\n 'package.json'\n );\n\n // Generate a package.json if option has been set.\n if (options.generatePackageJson) {\n if (context.projectGraph.nodes[context.projectName].type !== 'app') {\n logger.warn(\n stripIndents`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.\n For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`\n );\n }\n\n const builtPackageJson = createPackageJson(\n context.projectName,\n context.projectGraph,\n {\n target: context.targetName,\n root: context.root,\n isProduction: !options.includeDevDependenciesInPackageJson, // By default we remove devDependencies since this is a production build.\n skipOverrides: options.skipOverrides,\n skipPackageManager: options.skipPackageManager,\n }\n );\n\n builtPackageJson.type ??= 'module';\n\n writeJsonFile(\n `${outDirRelativeToWorkspaceRoot}/package.json`,\n builtPackageJson\n );\n const packageManager = detectPackageManager(context.root);\n\n const lockFile = createLockFile(\n builtPackageJson,\n context.projectGraph,\n packageManager\n );\n writeFileSync(\n `${outDirRelativeToWorkspaceRoot}/${getLockFileName(packageManager)}`,\n lockFile,\n {\n encoding: 'utf-8',\n }\n );\n }\n // For buildable libs, copy package.json if it exists.\n else if (\n options.generatePackageJson !== false &&\n !existsSync(distPackageJson) &&\n existsSync(libraryPackageJson) &&\n rootPackageJson !== libraryPackageJson\n ) {\n await copyAssets(\n {\n outputPath: outDirRelativeToWorkspaceRoot,\n assets: [\n {\n input: projectRoot,\n output: '.',\n glob: 'package.json',\n },\n ],\n },\n context\n );\n }\n\n const iterable = createAsyncIterable<{\n success: boolean;\n outfile?: string;\n }>(({ next, done }) => {\n if ('on' in watcherOrOutput) {\n let success = true;\n watcherOrOutput.on('event', (event) => {\n if (event.code === 'START') {\n success = true;\n } else if (event.code === 'ERROR') {\n success = false;\n } else if (event.code === 'END') {\n next({ success });\n }\n // result must be closed when present.\n // see https://rollupjs.org/guide/en/#rollupwatch\n if ('result' in event && event.result) {\n event.result.close();\n }\n });\n } else {\n const output =\n watcherOrOutput?.['output'] || watcherOrOutput?.[0]?.output;\n const fileName = output?.[0]?.fileName || 'main.cjs';\n const outfile = resolve(outDirRelativeToWorkspaceRoot, fileName);\n next({ success: true, outfile });\n done();\n }\n });\n iterables.push(iterable);\n }\n return yield* combineAsyncIterables(iterables.shift(), ...(iterables ?? []));\n}\n\nexport async function getBuildExtraArgs(\n options: ViteBuildExecutorOptions\n): Promise<{\n // vite BuildOptions\n buildOptions: Record<string, unknown>;\n otherOptions: Record<string, any>;\n}> {\n // support passing extra args to vite cli\n const schema = await import('./schema.json');\n const extraArgs = {};\n for (const key of Object.keys(options)) {\n if (!schema.properties[key]) {\n extraArgs[key] = options[key];\n }\n }\n\n const buildOptions = {};\n const buildSchemaKeys = [\n 'target',\n 'polyfillModulePreload',\n 'modulePreload',\n 'outDir',\n 'assetsDir',\n 'assetsInlineLimit',\n 'cssCodeSplit',\n 'cssTarget',\n 'cssMinify',\n 'sourcemap',\n 'minify',\n 'terserOptions',\n 'rollupOptions',\n 'commonjsOptions',\n 'dynamicImportVarsOptions',\n 'write',\n 'emptyOutDir',\n 'copyPublicDir',\n 'manifest',\n 'lib',\n 'ssr',\n 'ssrManifest',\n 'ssrEmitAssets',\n 'reportCompressedSize',\n 'chunkSizeWarningLimit',\n 'watch',\n ];\n const otherOptions = {};\n for (const key of Object.keys(extraArgs)) {\n if (buildSchemaKeys.includes(key)) {\n buildOptions[key] = extraArgs[key];\n } else {\n otherOptions[key] = extraArgs[key];\n }\n }\n\n buildOptions['watch'] = options.watch ?? undefined;\n\n return {\n buildOptions,\n otherOptions,\n };\n}\n\nexport default viteBuildExecutor;\n"],"names":["getBuildExtraArgs","viteBuildExecutor","options","context","resolved","process","env","VITE_CJS_IGNORE_WARNING","mergeConfig","build","resolveConfig","createBuilder","loadViteDynamicImport","projectRoot","projectsConfigurations","projects","projectName","root","tsConfigForBuild","createBuildableTsConfig","viteConfigPath","normalizeViteConfigFilePath","configFile","cwd","relative","joinPathFragments","buildOptions","otherOptions","defaultMode","mode","NODE_ENV","outDir","offsetFromRoot","outputPath","buildConfig","skipTypeCheck","isUsingTsSolutionSetup","validateTypes","workspaceRoot","tsconfig","isVueProject","Boolean","plugins","find","plugin","name","builder","undefined","useEnvironmentsApi","inlineConfig","environments","iterables","Object","values","config","watcherOrOutput","libraryPackageJson","resolve","rootPackageJson","outDirRelativeToWorkspaceRoot","replaceAll","distPackageJson","generatePackageJson","builtPackageJson","projectGraph","nodes","type","logger","warn","stripIndents","createPackageJson","target","targetName","isProduction","includeDevDependenciesInPackageJson","skipOverrides","skipPackageManager","writeJsonFile","packageManager","detectPackageManager","lockFile","createLockFile","writeFileSync","getLockFileName","encoding","existsSync","copyAssets","assets","input","output","glob","iterable","createAsyncIterable","next","done","success","on","event","code","result","close","fileName","outfile","push","combineAsyncIterables","shift","schema","extraArgs","key","keys","properties","buildSchemaKeys","includes","watch"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAySA,OAAiC;eAAjC;;IA9DsBA,iBAAiB;eAAjBA;;IAzMCC,iBAAiB;eAAjBA;;;;wBA1BhB;8BAIA;oBAOA;oBACmC;sBACR;+BAI3B;+BAKA;iCAEgC;AAEhC,gBAAgBA,kBACrBC,OAAuD,EACvDC,OAAwB;QAuCtBC;IArCFC,QAAQC,GAAG,CAACC,uBAAuB,GAAG;IACtC,yFAAyF;IACzF,MAAM,EAAEC,WAAW,EAAEC,KAAK,EAAEC,aAAa,EAAEC,aAAa,EAAE,GACxD,MAAMC,IAAAA,oCAAqB;IAC7B,MAAMC,cACJV,QAAQW,sBAAsB,CAACC,QAAQ,CAACZ,QAAQa,WAAW,CAAC,CAACC,IAAI;IACnE,MAAMC,mBAAmBC,IAAAA,sCAAuB,EAC9CN,aACA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pC;IACF;QAEwB1G;IAAxBwB,YAAY,CAAC,QAAQ,GAAGxB,CAAAA,iBAAAA,QAAQ+G,KAAK,YAAb/G,iBAAiB6C;IAEzC,OAAO;QACLrB;QACAC;IACF;AACF;MAEA,WAAe1B"}
|
|
@@ -67,6 +67,12 @@
|
|
|
67
67
|
"skipPackageManager": {
|
|
68
68
|
"type": "boolean",
|
|
69
69
|
"description": "Do not add a `packageManager` entry to the generated package.json file. Only works in conjunction with `generatePackageJson` option."
|
|
70
|
+
},
|
|
71
|
+
"useEnvironmentsApi": {
|
|
72
|
+
"alias": "app",
|
|
73
|
+
"type": "boolean",
|
|
74
|
+
"description": "Use the new Environments API for building multiple environments at once. Only works with Vite 6.0.0 or higher.",
|
|
75
|
+
"default": false
|
|
70
76
|
}
|
|
71
77
|
},
|
|
72
78
|
"definitions": {},
|
|
@@ -53,16 +53,23 @@ async function getOptions(options, context, projectRoot) {
|
|
|
53
53
|
]), { options: { watch } } = _parseCLI, normalizedExtraArgs = _object_without_properties_loose._(_parseCLI.options, [
|
|
54
54
|
"watch"
|
|
55
55
|
]);
|
|
56
|
+
const { reportsDirectory, coverage } = normalizedExtraArgs, restNormalizedArgs = _object_without_properties_loose._(normalizedExtraArgs, [
|
|
57
|
+
"reportsDirectory",
|
|
58
|
+
"coverage"
|
|
59
|
+
]);
|
|
56
60
|
var _resolved_config_root;
|
|
57
61
|
const settings = _extends._({
|
|
58
62
|
// Explicitly set watch mode to false if not provided otherwise vitest
|
|
59
63
|
// will enable watch mode by default for non CI environments
|
|
60
64
|
watch: watch != null ? watch : false
|
|
61
|
-
},
|
|
65
|
+
}, restNormalizedArgs, {
|
|
62
66
|
// This should not be needed as it's going to be set in vite.config.ts
|
|
63
67
|
// but leaving it here in case someone did not migrate correctly
|
|
64
68
|
root: (_resolved_config_root = resolved.config.root) != null ? _resolved_config_root : root,
|
|
65
|
-
config: viteConfigPath
|
|
69
|
+
config: viteConfigPath,
|
|
70
|
+
coverage: _extends._({}, coverage != null ? coverage : {}, reportsDirectory && {
|
|
71
|
+
reportsDirectory
|
|
72
|
+
})
|
|
66
73
|
});
|
|
67
74
|
var _resolved_config_test;
|
|
68
75
|
return mergeConfig((_resolved_config_test = resolved == null ? void 0 : (_resolved_config1 = resolved.config) == null ? void 0 : _resolved_config1['test']) != null ? _resolved_config_test : {}, settings);
|