Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

22
node_modules/@nx/vite/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2017-2026 Narwhal Technologies Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

68
node_modules/@nx/vite/README.md generated vendored Normal file
View File

@@ -0,0 +1,68 @@
<p style="text-align: center;">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-dark.svg">
<img alt="Nx - Smart Monorepos · Fast Builds" src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-light.svg" width="100%">
</picture>
</p>
<div style="text-align: center;">
[![CircleCI](https://circleci.com/gh/nrwl/nx.svg?style=svg)](https://circleci.com/gh/nrwl/nx)
[![License](https://img.shields.io/npm/l/@nx/workspace.svg?style=flat-square)]()
[![NPM Version](https://badge.fury.io/js/nx.svg)](https://www.npmjs.com/package/nx)
[![Semantic Release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)]()
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
[![Join the chat at https://gitter.im/nrwl-nx/community](https://badges.gitter.im/nrwl-nx/community.svg)](https://gitter.im/nrwl-nx/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Join us on the Official Nx Discord Server](https://img.shields.io/discord/1143497901675401286?label=discord)](https://go.nx.dev/community)
</div>
<hr>
# Nx: Smart Monorepos · Fast Builds
Get to green PRs in half the time. Nx optimizes your builds, scales your CI, and fixes failed PRs. Built for developers and AI agents.
This package is a [Vite plugin for Nx](https://nx.dev/nx-api/vite).
## Getting Started
### Creating an Nx Workspace
**Using `npx`**
```bash
npx create-nx-workspace
```
**Using `npm init`**
```bash
npm init nx-workspace
```
**Using `yarn create`**
```bash
yarn create nx-workspace
```
### Adding Nx to an Existing Repository
Run:
```bash
npx nx@latest init
```
## Documentation & Resources
- [Nx.Dev: Documentation, Guides, Tutorials](https://nx.dev)
- [Intro to Nx](https://nx.dev/getting-started/intro)
- [Official Nx YouTube Channel](https://www.youtube.com/@NxDevtools)
- [Blog Posts About Nx](https://nx.dev/blog)
<p style="text-align: center;"><a href="https://nx.dev/#learning-materials" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-courses-and-videos.svg"
width="100%" alt="Nx - Smart Monorepos · Fast Builds"></a></p>

9
node_modules/@nx/vite/executors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export { type ViteBuildExecutorOptions } from './src/executors/build/schema';
export { viteBuildExecutor } from './src/executors/build/build.impl';
export { type ViteDevServerExecutorOptions } from './src/executors/dev-server/schema';
export { viteDevServerExecutor } from './src/executors/dev-server/dev-server.impl';
export { type VitePreviewServerExecutorOptions } from './src/executors/preview-server/schema';
export { vitePreviewServerExecutor } from './src/executors/preview-server/preview-server.impl';
export { type VitestExecutorOptions } from './src/executors/test/schema';
export { vitestExecutor } from './src/executors/test/vitest.impl';
//# sourceMappingURL=executors.d.ts.map

1
node_modules/@nx/vite/executors.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"executors.d.ts","sourceRoot":"","sources":["../../../packages/vite/executors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EAAE,KAAK,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACtF,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,KAAK,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,EAAE,yBAAyB,EAAE,MAAM,oDAAoD,CAAC;AAC/F,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC"}

11
node_modules/@nx/vite/executors.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.vitestExecutor = exports.vitePreviewServerExecutor = exports.viteDevServerExecutor = exports.viteBuildExecutor = void 0;
var build_impl_1 = require("./src/executors/build/build.impl");
Object.defineProperty(exports, "viteBuildExecutor", { enumerable: true, get: function () { return build_impl_1.viteBuildExecutor; } });
var dev_server_impl_1 = require("./src/executors/dev-server/dev-server.impl");
Object.defineProperty(exports, "viteDevServerExecutor", { enumerable: true, get: function () { return dev_server_impl_1.viteDevServerExecutor; } });
var preview_server_impl_1 = require("./src/executors/preview-server/preview-server.impl");
Object.defineProperty(exports, "vitePreviewServerExecutor", { enumerable: true, get: function () { return preview_server_impl_1.vitePreviewServerExecutor; } });
var vitest_impl_1 = require("./src/executors/test/vitest.impl");
Object.defineProperty(exports, "vitestExecutor", { enumerable: true, get: function () { return vitest_impl_1.vitestExecutor; } });

46
node_modules/@nx/vite/executors.json generated vendored Normal file
View File

@@ -0,0 +1,46 @@
{
"builders": {
"dev-server": {
"implementation": "./src/executors/dev-server/compat",
"schema": "./src/executors/dev-server/schema.json",
"description": "Vite dev server."
},
"build": {
"implementation": "./src/executors/build/compat",
"schema": "./src/executors/build/schema.json",
"description": "Build with Vite."
},
"test": {
"implementation": "./src/executors/test/compat",
"schema": "./src/executors/test/schema.json",
"description": "Test with Vitest"
},
"preview-server": {
"implementation": "./src/executors/preview-server/compat",
"schema": "./src/executors/preview-server/schema.json",
"description": "Vite preview server"
}
},
"executors": {
"dev-server": {
"implementation": "./src/executors/dev-server/dev-server.impl",
"schema": "./src/executors/dev-server/schema.json",
"description": "Vite dev server."
},
"build": {
"implementation": "./src/executors/build/build.impl",
"schema": "./src/executors/build/schema.json",
"description": "Build with Vite."
},
"test": {
"implementation": "./src/executors/test/vitest.impl",
"schema": "./src/executors/test/schema.json",
"description": "Test with Vitest"
},
"preview-server": {
"implementation": "./src/executors/preview-server/preview-server.impl",
"schema": "./src/executors/preview-server/schema.json",
"description": "Vite preview server"
}
}
}

35
node_modules/@nx/vite/generators.json generated vendored Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "Nx Vite",
"version": "0.1",
"generators": {
"init": {
"factory": "./src/generators/init/init#initGeneratorInternal",
"schema": "./src/generators/init/schema.json",
"description": "Initialize Vite in the workspace.",
"aliases": ["ng-add"],
"hidden": true
},
"configuration": {
"factory": "./src/generators/configuration/configuration#viteConfigurationGeneratorInternal",
"schema": "./src/generators/configuration/schema.json",
"description": "Add Vite configuration to an application.",
"aliases": ["config"],
"hidden": false
},
"setup-paths-plugin": {
"factory": "./src/generators/setup-paths-plugin/setup-paths-plugin",
"schema": "./src/generators/setup-paths-plugin/schema.json",
"description": "Sets up the nxViteTsPaths plugin to enable support for workspace libraries."
},
"convert-to-inferred": {
"factory": "./src/generators/convert-to-inferred/convert-to-inferred",
"schema": "./src/generators/convert-to-inferred/schema.json",
"description": "Convert existing Vite project(s) using `@nx/vite:*` executors to use `@nx/vite/plugin`. Defaults to migrating all projects. Pass '--project' to migrate only one target."
},
"vitest": {
"factory": "./src/generators/vitest/vitest-generator",
"schema": "./src/generators/vitest/schema.json",
"description": "Generate a vitest configuration."
}
}
}

10
node_modules/@nx/vite/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
export * from './src/utils/versions';
export * from './src/utils/generator-utils';
export * from './src/utils/e2e-web-server-info-utils';
export { type ViteConfigurationGeneratorSchema } from './src/generators/configuration/schema';
export { viteConfigurationGenerator } from './src/generators/configuration/configuration';
export { type VitestGeneratorSchema } from './src/generators/vitest/schema';
export { vitestGenerator } from './src/generators/vitest/vitest-generator';
export { type InitGeneratorSchema } from './src/generators/init/schema';
export { initGenerator } from './src/generators/init/init';
//# sourceMappingURL=index.d.ts.map

1
node_modules/@nx/vite/index.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../packages/vite/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,uCAAuC,CAAC;AACtD,OAAO,EAAE,KAAK,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAC1F,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAC3E,OAAO,EAAE,KAAK,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC"}

13
node_modules/@nx/vite/index.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initGenerator = exports.vitestGenerator = exports.viteConfigurationGenerator = void 0;
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./src/utils/versions"), exports);
tslib_1.__exportStar(require("./src/utils/generator-utils"), exports);
tslib_1.__exportStar(require("./src/utils/e2e-web-server-info-utils"), exports);
var configuration_1 = require("./src/generators/configuration/configuration");
Object.defineProperty(exports, "viteConfigurationGenerator", { enumerable: true, get: function () { return configuration_1.viteConfigurationGenerator; } });
var vitest_generator_1 = require("./src/generators/vitest/vitest-generator");
Object.defineProperty(exports, "vitestGenerator", { enumerable: true, get: function () { return vitest_generator_1.vitestGenerator; } });
var init_1 = require("./src/generators/init/init");
Object.defineProperty(exports, "initGenerator", { enumerable: true, get: function () { return init_1.initGenerator; } });

154
node_modules/@nx/vite/migrations.json generated vendored Normal file
View File

@@ -0,0 +1,154 @@
{
"generators": {
"update-20-0-4": {
"version": "20.0.4-beta.0",
"description": "Add gitignore entry for temporary vite config files.",
"implementation": "./src/migrations/update-20-0-4/add-vite-temp-files-to-git-ignore"
},
"update-20-0-6": {
"version": "20.0.6-beta.0",
"description": "Add gitignore entry for temporary vite config files and remove previous incorrect glob.",
"implementation": "./src/migrations/update-20-0-4/add-vite-temp-files-to-git-ignore"
},
"update-20-5-0-install-jiti": {
"version": "20.5.0-beta.2",
"description": "Install jiti as a devDependency to allow vite to parse TS postcss files.",
"implementation": "./src/migrations/update-20-5-0/install-jiti"
},
"update-20-5-0-update-resolve-conditions": {
"version": "20.5.0-beta.3",
"description": "Update resolve.conditions to include defaults that are no longer provided by Vite.",
"implementation": "./src/migrations/update-20-5-0/update-resolve-conditions"
},
"eslint-ignore-vite-temp-files": {
"version": "20.5.0-beta.3",
"description": "Add vite config temporary files to the ESLint configuration ignore patterns if ESLint is used.",
"implementation": "./src/migrations/update-20-5-0/eslint-ignore-vite-temp-files"
},
"update-22-2-0": {
"version": "22.2.0-beta.1",
"requires": {
"vitest": ">=4.0.0"
},
"description": "Create AI Instructions to help migrate users workspaces past breaking changes for Vitest 4.",
"implementation": "./src/migrations/update-22-2-0/create-ai-instructions-for-vitest-4"
},
"migrate-vitest-to-vitest-package": {
"version": "22.2.0-beta.2",
"description": "Migrate Vitest usage from @nx/vite to @nx/vitest package.",
"implementation": "./src/migrations/update-22-2-0/migrate-vitest-to-vitest-package"
}
},
"packageJsonUpdates": {
"20.7.1": {
"version": "20.7.1-beta.0",
"packages": {
"@analogjs/vite-plugin-angular": {
"version": "~1.14.1",
"alwaysAddToPackageJson": false
},
"@analogjs/vitest-angular": {
"version": "~1.14.1",
"alwaysAddToPackageJson": false
}
}
},
"20.5.0": {
"version": "20.5.0-beta.3",
"packages": {
"vite": {
"version": "^6.0.0",
"alwaysAddToPackageJson": false
},
"vite-plugin-dts": {
"version": "~4.5.0",
"alwaysAddToPackageJson": false
}
}
},
"21.1.2": {
"version": "21.1.2-beta.0",
"packages": {
"@analogjs/vitest-angular": {
"version": "~1.16.1",
"alwaysAddToPackageJson": false
}
}
},
"21.2.0": {
"version": "21.2.0-beta.3",
"packages": {
"@analogjs/vite-plugin-angular": {
"version": "~1.17.1",
"alwaysAddToPackageJson": false
},
"@analogjs/vitest-angular": {
"version": "~1.17.1",
"alwaysAddToPackageJson": false
}
}
},
"21.3.0": {
"version": "21.3.0-beta.3",
"packages": {
"@analogjs/vite-plugin-angular": {
"version": "~1.19.1",
"alwaysAddToPackageJson": false
},
"@analogjs/vitest-angular": {
"version": "~1.19.1",
"alwaysAddToPackageJson": false
}
}
},
"21.5.0": {
"version": "21.5.0-beta.0",
"packages": {
"vite": {
"version": "^7.1.3",
"alwaysAddToPackageJson": false
}
},
"incompatibleWith": {
"@remix-run/dev": "*"
}
},
"22.2.0": {
"version": "22.2.0-beta.1",
"requires": {
"vitest": ">=3.0.0"
},
"packages": {
"vitest": {
"version": "^4.0.0",
"alwaysAddToPackageJson": false
},
"@vitest/coverage-v8": {
"version": "^4.0.0",
"alwaysAddToPackageJson": false
},
"@vitest/coverage-istanbul": {
"version": "^4.0.0",
"alwaysAddToPackageJson": false
},
"@vitest/ui": {
"version": "^4.0.0",
"alwaysAddToPackageJson": false
}
}
},
"22.2.0-analog": {
"version": "22.2.0-beta.3",
"packages": {
"@analogjs/vite-plugin-angular": {
"version": "~2.1.2",
"alwaysAddToPackageJson": false
},
"@analogjs/vitest-angular": {
"version": "~2.1.2",
"alwaysAddToPackageJson": false
}
}
}
}
}

73
node_modules/@nx/vite/package.json generated vendored Normal file
View File

@@ -0,0 +1,73 @@
{
"name": "@nx/vite",
"version": "22.7.5",
"private": false,
"description": "The Nx Plugin for building and testing applications using Vite",
"repository": {
"type": "git",
"url": "https://github.com/nrwl/nx.git",
"directory": "packages/vite"
},
"keywords": [
"Monorepo",
"Vite",
"Web",
"CLI",
"Front-end"
],
"main": "./index.js",
"type": "commonjs",
"types": "./index.d.ts",
"author": "Victor Savkin",
"license": "MIT",
"bugs": {
"url": "https://github.com/nrwl/nx/issues"
},
"homepage": "https://nx.dev",
"generators": "./generators.json",
"executors": "./executors.json",
"ng-update": {
"requirements": {},
"migrations": "./migrations.json"
},
"dependencies": {
"@nx/devkit": "22.7.5",
"@phenomnomnominal/tsquery": "~6.2.0",
"enquirer": "~2.3.6",
"@nx/js": "22.7.5",
"@nx/vitest": "22.7.5",
"picomatch": "4.0.4",
"tsconfig-paths": "^4.1.2",
"semver": "^7.6.3",
"tslib": "^2.3.0",
"ajv": "^8.0.0"
},
"devDependencies": {
"nx": "22.7.5"
},
"peerDependencies": {
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0",
"vitest": "^1.3.1 || ^2.0.0 || ^3.0.0 || ^4.0.0"
},
"publishConfig": {
"access": "public"
},
"exports": {
".": "./index.js",
"./plugin": "./plugin.js",
"./package.json": "./package.json",
"./migrations.json": "./migrations.json",
"./generators.json": "./generators.json",
"./executors.json": "./executors.json",
"./executors": "./executors.js",
"./src/executors/*/schema.json": "./src/executors/*/schema.json",
"./src/executors/*.impl": "./src/executors/*.impl.js",
"./src/executors/*/schema": "./src/executors/*/schema.d.ts",
"./src/executors/*/compat": "./src/executors/*/compat.js",
"./src/generators/*/schema.json": "./src/generators/*/schema.json",
"./src/generators/*/schema": "./src/generators/*/schema.d.ts",
"./plugins/nx-copy-assets.plugin": "./plugins/nx-copy-assets.plugin.js",
"./plugins/nx-tsconfig-paths.plugin": "./plugins/nx-tsconfig-paths.plugin.js",
"./plugins/rollup-replace-files.plugin": "./plugins/rollup-replace-files.plugin.js"
}
}

2
node_modules/@nx/vite/plugin.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export { createNodes, createNodesV2, VitePluginOptions, createDependencies, } from './src/plugins/plugin';
//# sourceMappingURL=plugin.d.ts.map

1
node_modules/@nx/vite/plugin.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../packages/vite/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,aAAa,EACb,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,sBAAsB,CAAC"}

7
node_modules/@nx/vite/plugin.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDependencies = exports.createNodesV2 = exports.createNodes = void 0;
var plugin_1 = require("./src/plugins/plugin");
Object.defineProperty(exports, "createNodes", { enumerable: true, get: function () { return plugin_1.createNodes; } });
Object.defineProperty(exports, "createNodesV2", { enumerable: true, get: function () { return plugin_1.createNodesV2; } });
Object.defineProperty(exports, "createDependencies", { enumerable: true, get: function () { return plugin_1.createDependencies; } });

View File

@@ -0,0 +1,4 @@
import type { Plugin } from 'vite';
import { AssetGlob } from '@nx/js/src/utils/assets/assets';
export declare function nxCopyAssetsPlugin(_assets: (string | AssetGlob)[]): Plugin;
//# sourceMappingURL=nx-copy-assets.plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nx-copy-assets.plugin.d.ts","sourceRoot":"","sources":["../../../../packages/vite/plugins/nx-copy-assets.plugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAC;AAEnD,OAAO,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAG3D,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GAAG,MAAM,CA2C1E"}

50
node_modules/@nx/vite/plugins/nx-copy-assets.plugin.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nxCopyAssetsPlugin = nxCopyAssetsPlugin;
const node_path_1 = require("node:path");
const devkit_1 = require("@nx/devkit");
const copy_assets_handler_1 = require("@nx/js/src/utils/assets/copy-assets-handler");
function nxCopyAssetsPlugin(_assets) {
let config;
let handler;
let dispose;
if (global.NX_GRAPH_CREATION)
return;
return {
name: 'nx-copy-assets-plugin',
configResolved(_config) {
config = _config;
},
async buildStart() {
const relativeProjectRoot = (0, node_path_1.relative)(devkit_1.workspaceRoot, config.root);
const assets = _assets.map((a) => {
if (typeof a === 'string') {
return (0, devkit_1.joinPathFragments)(relativeProjectRoot, a);
}
else {
return {
...a,
input: (0, devkit_1.joinPathFragments)(relativeProjectRoot, a.input),
};
}
});
handler = new copy_assets_handler_1.CopyAssetsHandler({
rootDir: devkit_1.workspaceRoot,
projectDir: config.root,
outputDir: config.build.outDir.startsWith(config.root)
? config.build.outDir
: (0, node_path_1.join)(config.root, config.build.outDir),
assets,
});
if (this.meta.watchMode && (0, devkit_1.isDaemonEnabled)()) {
dispose = await handler.watchAndProcessOnAssetChange();
}
},
async writeBundle() {
await handler.processAllAssetsOnce();
},
async closeWatcher() {
dispose == null ? void 0 : dispose();
},
};
}

View File

@@ -0,0 +1,29 @@
import { Plugin } from 'vite';
export interface nxViteTsPathsOptions {
/**
* Enable debug logging
* If set to false, it will always ignore the debug logging even when `--verbose` or `NX_VERBOSE_LOGGING` is set to true.
* @default undefined
**/
debug?: boolean;
/**
* export fields in package.json to use for resolving
* @default [['exports', '.', 'import'], 'module', 'main']
*
* fallback resolution will use ['main', 'module']
**/
mainFields?: (string | string[])[];
/**
* extensions to check when resolving files when package.json resolution fails
* @default ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs', '.cjs']
**/
extensions?: string[];
/**
* Inform Nx whether to use the raw source or to use the built output for buildable dependencies.
* Set to `false` to use incremental builds.
* @default true
*/
buildLibsFromSource?: boolean;
}
export declare function nxViteTsPaths(options?: nxViteTsPathsOptions): Plugin;
//# sourceMappingURL=nx-tsconfig-paths.plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nx-tsconfig-paths.plugin.d.ts","sourceRoot":"","sources":["../../../../packages/vite/plugins/nx-tsconfig-paths.plugin.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAK9B,MAAM,WAAW,oBAAoB;IACnC;;;;QAII;IACJ,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;;;;QAKI;IACJ,UAAU,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,CAAC;IACnC;;;QAGI;IACJ,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED,wBAAgB,aAAa,CAAC,OAAO,GAAE,oBAAyB,GA4KzD,MAAM,CA0EZ"}

View File

@@ -0,0 +1,193 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nxViteTsPaths = nxViteTsPaths;
const devkit_1 = require("@nx/devkit");
const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
const ts_config_1 = require("@nx/js/src/utils/typescript/ts-config");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const tsconfig_paths_1 = require("tsconfig-paths");
const nx_tsconfig_paths_find_file_1 = require("../src/utils/nx-tsconfig-paths-find-file");
const options_utils_1 = require("../src/utils/options-utils");
const nx_vite_build_coordination_plugin_1 = require("./nx-vite-build-coordination.plugin");
function nxViteTsPaths(options = {}) {
let foundTsConfigPath;
let matchTsPathEsm;
let matchTsPathFallback;
let tsConfigPathsEsm;
let tsConfigPathsFallback;
options.extensions ??= [
'.ts',
'.tsx',
'.js',
'.jsx',
'.json',
'.mts',
'.mjs',
'.cts',
'.cjs',
'.css',
'.scss',
'.less',
];
options.mainFields ??= [['exports', '.', 'import'], 'module', 'main'];
options.buildLibsFromSource ??= true;
let projectRoot = '';
let projectRootFromWorkspaceRoot;
return {
name: 'nx-vite-ts-paths',
// Ensure the resolveId aspect of the plugin is called before vite's internal resolver
// Otherwise, issues can arise with Yarn Workspaces and Pnpm Workspaces
enforce: 'pre',
async configResolved(config) {
projectRoot = config.root;
projectRootFromWorkspaceRoot = (0, node_path_1.relative)(devkit_1.workspaceRoot, projectRoot);
foundTsConfigPath = getTsConfig(process.env.NX_TSCONFIG_PATH ??
(0, node_path_1.join)(devkit_1.workspaceRoot, 'tmp', projectRootFromWorkspaceRoot, process.env.NX_TASK_TARGET_TARGET ?? 'build', 'tsconfig.generated.json'));
if (!foundTsConfigPath)
return;
if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION) {
const projectGraph = await (0, devkit_1.createProjectGraphAsync)({
exitOnError: false,
resetDaemonClient: true,
});
// When using incremental building and the serve target is called
// we need to get the deps for the 'build' target instead.
const depsBuildTarget = process.env.NX_TASK_TARGET_TARGET === 'serve' ||
process.env.NX_TASK_TARGET_TARGET === 'test'
? 'build'
: process.env.NX_TASK_TARGET_TARGET;
const { dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(undefined, projectGraph, devkit_1.workspaceRoot, process.env.NX_TASK_TARGET_PROJECT, depsBuildTarget, process.env.NX_TASK_TARGET_CONFIGURATION);
if (process.env.NX_GENERATED_TSCONFIG_PATH) {
// This is needed for vitest browser mode because it runs two vite dev servers
// so we want to reuse the same tsconfig file for both servers
foundTsConfigPath = process.env.NX_GENERATED_TSCONFIG_PATH;
}
else {
// This tsconfig is used via the Vite ts paths plugin.
// It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).
foundTsConfigPath = (0, buildable_libs_utils_1.createTmpTsConfig)(foundTsConfigPath, devkit_1.workspaceRoot, (0, node_path_1.relative)(devkit_1.workspaceRoot, projectRoot), dependencies, true);
process.env.NX_GENERATED_TSCONFIG_PATH = foundTsConfigPath;
}
if (config.command === 'serve') {
const buildableLibraryDependencies = dependencies
.filter((dep) => dep.node.type === 'lib')
.map((dep) => dep.node.name)
.join(',');
const buildCommand = `npx nx run-many --target=${depsBuildTarget} --projects=${buildableLibraryDependencies}`;
config.plugins.push((0, nx_vite_build_coordination_plugin_1.nxViteBuildCoordinationPlugin)({ buildCommand }));
}
}
const parsed = (0, tsconfig_paths_1.loadConfig)(foundTsConfigPath);
logIt('first parsed tsconfig: ', parsed);
if (parsed.resultType === 'failed') {
throw new Error(`Failed loading tsconfig at ${foundTsConfigPath}`);
}
tsConfigPathsEsm = parsed;
matchTsPathEsm = (0, tsconfig_paths_1.createMatchPath)((0, ts_config_1.resolvePathsBaseUrl)(foundTsConfigPath), parsed.paths, options.mainFields);
const rootLevelTsConfig = getTsConfig((0, node_path_1.join)(devkit_1.workspaceRoot, 'tsconfig.base.json'));
const rootLevelParsed = (0, tsconfig_paths_1.loadConfig)(rootLevelTsConfig);
logIt('fallback parsed tsconfig: ', rootLevelParsed);
if (rootLevelParsed.resultType === 'success') {
tsConfigPathsFallback = rootLevelParsed;
matchTsPathFallback = (0, tsconfig_paths_1.createMatchPath)((0, ts_config_1.resolvePathsBaseUrl)(rootLevelTsConfig), rootLevelParsed.paths, ['main', 'module']);
}
},
resolveId(importPath) {
// Let other resolvers handle this path.
if (!foundTsConfigPath)
return null;
// Skip absolute and root-relative paths — these are filesystem paths,
// not TypeScript import specifiers. In Vite, `/foo` is a project-root-
// relative URL and must be resolved by Vite's built-in resolver, not
// by tsconfig path mapping (which would incorrectly use baseUrl).
if (importPath.startsWith('/'))
return null;
let resolvedFile;
try {
resolvedFile = matchTsPathEsm(importPath);
}
catch (e) {
logIt('Using fallback path matching.');
resolvedFile = matchTsPathFallback?.(importPath);
}
if (!resolvedFile || !(0, node_fs_1.existsSync)(resolvedFile)) {
if (tsConfigPathsEsm || tsConfigPathsFallback) {
logIt(`Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`);
resolvedFile =
loadFileFromPaths(tsConfigPathsEsm, importPath) ||
loadFileFromPaths(tsConfigPathsFallback, importPath);
}
else {
logIt(`Unable to resolve ${importPath} with tsconfig paths`);
}
}
logIt(`Resolved ${importPath} to ${resolvedFile}`);
// Returning null defers to other resolveId functions and eventually the default resolution behavior
// https://rollupjs.org/plugin-development/#resolveid
return resolvedFile || null;
},
async writeBundle(options) {
if ((0, ts_solution_setup_1.isUsingTsSolutionSetup)())
return;
const outDir = options.dir || 'dist';
const src = (0, node_path_1.resolve)(projectRoot, 'package.json');
const dest = (0, node_path_1.join)(outDir, 'package.json');
if ((0, node_fs_1.existsSync)(src) && !(0, node_fs_1.existsSync)(dest)) {
try {
(0, node_fs_1.copyFileSync)(src, dest);
}
catch (err) {
console.error('Error copying package.json:', err);
}
}
},
};
function getTsConfig(preferredTsConfigPath) {
const projectTsConfigPath = (0, options_utils_1.getProjectTsConfigPath)(projectRootFromWorkspaceRoot);
return [
(0, node_path_1.resolve)(preferredTsConfigPath),
projectTsConfigPath
? (0, node_path_1.resolve)((0, node_path_1.join)(devkit_1.workspaceRoot, projectTsConfigPath))
: null,
(0, node_path_1.resolve)((0, node_path_1.join)(devkit_1.workspaceRoot, 'tsconfig.base.json')),
(0, node_path_1.resolve)((0, node_path_1.join)(devkit_1.workspaceRoot, 'tsconfig.json')),
(0, node_path_1.resolve)((0, node_path_1.join)(devkit_1.workspaceRoot, 'jsconfig.json')),
]
.filter(Boolean)
.find((tsPath) => {
if ((0, node_fs_1.existsSync)(tsPath)) {
logIt('Found tsconfig at', tsPath);
return tsPath;
}
});
}
function logIt(...msg) {
if (process.env.NX_VERBOSE_LOGGING === 'true' && options?.debug !== false) {
console.debug('\n[Nx Vite TsPaths]', ...msg);
}
}
function loadFileFromPaths(tsconfig, importPath) {
logIt(`Trying to resolve file from config in ${tsconfig.configFileAbsolutePath}`);
let resolvedFile;
for (const alias in tsconfig.paths) {
const paths = tsconfig.paths[alias];
const normalizedImport = alias.replace(/\/\*$/, '');
if (importPath === normalizedImport ||
importPath.startsWith(normalizedImport + '/')) {
const joinedPath = (0, devkit_1.joinPathFragments)(tsconfig.absoluteBaseUrl, paths[0].replace(/\/\*$/, ''));
resolvedFile = (0, nx_tsconfig_paths_find_file_1.findFile)(importPath.replace(normalizedImport, joinedPath), options.extensions);
if (resolvedFile === undefined &&
options.extensions.some((ext) => importPath.endsWith(ext))) {
const foundExtension = options.extensions.find((ext) => importPath.endsWith(ext));
const pathWithoutExtension = importPath
.replace(normalizedImport, joinedPath)
.slice(0, -foundExtension.length);
resolvedFile = (0, nx_tsconfig_paths_find_file_1.findFile)(pathWithoutExtension, options.extensions);
}
}
}
return resolvedFile;
}
}

View File

@@ -0,0 +1,6 @@
import { type Plugin } from 'vite';
export interface NxViteBuildCoordinationPluginOptions {
buildCommand: string;
}
export declare function nxViteBuildCoordinationPlugin(options: NxViteBuildCoordinationPluginOptions): Plugin;
//# sourceMappingURL=nx-vite-build-coordination.plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nx-vite-build-coordination.plugin.d.ts","sourceRoot":"","sources":["../../../../packages/vite/plugins/nx-vite-build-coordination.plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,MAAM,CAAC;AASnC,MAAM,WAAW,oCAAoC;IACnD,YAAY,EAAE,MAAM,CAAC;CACtB;AACD,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,oCAAoC,GAC5C,MAAM,CA0ER"}

View File

@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nxViteBuildCoordinationPlugin = nxViteBuildCoordinationPlugin;
const watch_1 = require("nx/src/command-line/watch/watch");
const child_process_1 = require("child_process");
const client_1 = require("nx/src/daemon/client/client");
const output_1 = require("nx/src/utils/output");
function nxViteBuildCoordinationPlugin(options) {
let activeBuildProcess;
let unregisterFileWatcher;
async function buildChangedProjects() {
await new Promise((res) => {
activeBuildProcess = (0, child_process_1.exec)(options.buildCommand, {
windowsHide: true,
});
activeBuildProcess.stdout.pipe(process.stdout);
activeBuildProcess.stderr.pipe(process.stderr);
activeBuildProcess.on('exit', () => {
res();
});
activeBuildProcess.on('error', () => {
res();
});
});
activeBuildProcess = undefined;
}
function createFileWatcher() {
const runner = new watch_1.BatchFunctionRunner(() => buildChangedProjects());
return client_1.daemonClient.registerFileWatcher({ watchProjects: 'all' }, (err, { changedProjects, changedFiles }) => {
if (err === 'reconnecting') {
// Silent - daemon restarts automatically on lockfile changes
return;
}
else if (err === 'reconnected') {
// Silent - reconnection succeeded
return;
}
else if (err === 'closed') {
output_1.output.error({
title: `Failed to reconnect to daemon after multiple attempts`,
});
process.exit(1);
}
else if (err) {
output_1.output.error({
title: `Watch error: ${err?.message ?? 'Unknown'}`,
});
}
if (activeBuildProcess) {
activeBuildProcess.kill(2);
activeBuildProcess = undefined;
}
runner.enqueue(changedProjects, changedFiles);
});
}
let firstBuildStart = true;
return {
name: 'nx-vite-build-coordination-plugin',
async buildStart() {
if (firstBuildStart) {
firstBuildStart = false;
await buildChangedProjects();
if (client_1.daemonClient.enabled()) {
unregisterFileWatcher = await createFileWatcher();
process.on('exit', () => unregisterFileWatcher());
process.on('SIGINT', () => process.exit());
}
else {
output_1.output.warn({
title: 'Nx Daemon is not enabled. Projects will not be rebuilt when files change.',
});
}
}
},
};
}

View File

@@ -0,0 +1,17 @@
/**
* @function replaceFiles
* @param {FileReplacement[]} replacements
* @return {({name: "rollup-plugin-replace-files", enforce: "pre" | "post" | undefined, Promise<resolveId>})}
*/
export declare function replaceFiles(replacements: FileReplacement[]): {
name: string;
enforce: 'pre' | 'post' | undefined;
resolveId(source: any, importer: any, options: any): Promise<{
id: string;
}>;
};
export interface FileReplacement {
replace: string;
with: string;
}
//# sourceMappingURL=rollup-replace-files.plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"rollup-replace-files.plugin.d.ts","sourceRoot":"","sources":["../../../../packages/vite/plugins/rollup-replace-files.plugin.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,YAAY,EAAE,eAAe,EAAE,GAAG;IAC7D,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,KAAK,GAAG,MAAM,GAAG,SAAS,CAAC;IACpC,SAAS,CACP,MAAM,EAAE,GAAG,EACX,QAAQ,EAAE,GAAG,EACb,OAAO,EAAE,GAAG,GACX,OAAO,CAAC;QACT,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC,CAAC;CACJ,CAuCA;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;CACd"}

View File

@@ -0,0 +1,45 @@
"use strict";
// source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceFiles = replaceFiles;
/**
* @function replaceFiles
* @param {FileReplacement[]} replacements
* @return {({name: "rollup-plugin-replace-files", enforce: "pre" | "post" | undefined, Promise<resolveId>})}
*/
function replaceFiles(replacements) {
if (!replacements?.length) {
return null;
}
return {
name: 'rollup-plugin-replace-files',
enforce: 'pre',
async resolveId(source, importer, options) {
const resolved = await this.resolve(source, importer, {
...options,
skipSelf: true,
});
/**
* The reason we're using endsWith here is because the resolved id
* will be the absolute path to the file. We want to check if the
* file ends with the file we're trying to replace, which will be essentially
* the path from the root of our workspace.
*/
const foundReplace = replacements.find((replacement) => resolved?.id?.endsWith(replacement.replace));
if (foundReplace) {
console.info(`replace "${foundReplace.replace}" with "${foundReplace.with}"`);
try {
// return new file content
return {
id: resolved.id.replace(foundReplace.replace, foundReplace.with),
};
}
catch (err) {
console.error(err);
return null;
}
}
return null;
},
};
}

View File

@@ -0,0 +1,12 @@
import { ExecutorContext } from '@nx/devkit';
import { ViteBuildExecutorOptions } from './schema';
export declare function viteBuildExecutor(options: Record<string, any> & ViteBuildExecutorOptions, context: ExecutorContext): AsyncGenerator<{
success: boolean;
outfile?: string;
}, any, any>;
export declare function getBuildExtraArgs(options: ViteBuildExecutorOptions): Promise<{
buildOptions: Record<string, unknown>;
otherOptions: Record<string, any>;
}>;
export default viteBuildExecutor;
//# sourceMappingURL=build.impl.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"build.impl.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/build/build.impl.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,EAMhB,MAAM,YAAY,CAAC;AAKpB,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAqBpD,wBAAuB,iBAAiB,CACtC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,wBAAwB,EACvD,OAAO,EAAE,eAAe;aA+EgB,OAAO;cAAY,MAAM;aAmIlE;AAED,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC;IAET,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CACnC,CAAC,CAuDD;AAED,eAAe,iBAAiB,CAAC"}

239
node_modules/@nx/vite/src/executors/build/build.impl.js generated vendored Normal file
View File

@@ -0,0 +1,239 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.viteBuildExecutor = viteBuildExecutor;
exports.getBuildExtraArgs = getBuildExtraArgs;
const devkit_1 = require("@nx/devkit");
const options_utils_1 = require("../../utils/options-utils");
const js_1 = require("@nx/js");
const fs_1 = require("fs");
const path_1 = require("path");
const async_iterable_1 = require("@nx/devkit/src/utils/async-iterable");
const executor_utils_1 = require("../../utils/executor-utils");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
async function* viteBuildExecutor(options, context) {
process.env.VITE_CJS_IGNORE_WARNING = 'true';
// Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
const { mergeConfig, build, resolveConfig, createBuilder } = await (0, executor_utils_1.loadViteDynamicImport)();
const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
const tsConfigForBuild = (0, executor_utils_1.createBuildableTsConfig)(projectRoot, options, context);
const viteConfigPath = (0, options_utils_1.normalizeViteConfigFilePath)(context.root, projectRoot, options.configFile);
const root = projectRoot === '.' || projectRoot === ''
? process.cwd()
: (0, path_1.relative)(context.cwd, (0, devkit_1.joinPathFragments)(context.root, projectRoot));
const { buildOptions, otherOptions } = await getBuildExtraArgs(options);
const defaultMode = otherOptions?.mode ?? 'production';
const resolved = await resolveConfig({
configFile: viteConfigPath,
mode: defaultMode,
}, 'build', defaultMode, process.env.NODE_ENV ?? defaultMode);
const outDir = (0, devkit_1.joinPathFragments)((0, devkit_1.offsetFromRoot)(projectRoot), options.outputPath) ??
resolved?.build?.outDir;
const buildConfig = mergeConfig({
// This should not be needed as it's going to be set in vite.config.ts
// but leaving it here in case someone did not migrate correctly
root: resolved.root ?? root,
configFile: viteConfigPath,
}, {
build: {
outDir,
...buildOptions,
},
...otherOptions,
});
// New TS Solution already has a typecheck target
if (!options.skipTypeCheck && !(0, ts_solution_setup_1.isUsingTsSolutionSetup)()) {
await (0, executor_utils_1.validateTypes)({
workspaceRoot: context.root,
tsconfig: tsConfigForBuild,
isVueProject: Boolean(resolved.plugins?.find((plugin) => typeof plugin === 'object' && plugin?.name === 'vite:vue')),
});
}
const builder = createBuilder !== undefined && options.useEnvironmentsApi
? await createBuilder(buildConfig)
: // This is needed to ensure support for Vite 5
{
build: (inlineConfig) => build(inlineConfig),
environments: { build: buildConfig },
};
let iterables = [];
for (const env of Object.values(builder.environments)) {
// Overwrite the resolved build config with executor options (e.g. outDir).
// Skip when using the builder API (Vite 8+) as the builder already
// resolves environment configs correctly and overwriting would clobber
// environment-specific options like rollupOptions/rolldownOptions.
if (env.config?.build && !options.useEnvironmentsApi) {
env.config.build = {
...env.config.build,
...buildConfig.build,
};
}
const watcherOrOutput = await builder.build(env);
const libraryPackageJson = (0, path_1.resolve)(projectRoot, 'package.json');
const rootPackageJson = (0, path_1.resolve)(context.root, 'package.json');
// Here, we want the outdir relative to the workspace root.
// So, we calculate the relative path from the workspace root to the outdir.
const absoluteOutDir = (0, path_1.resolve)((0, path_1.resolve)(context.root, projectRoot), outDir);
const outDirRelativeToWorkspaceRoot = (0, path_1.relative)(context.root, absoluteOutDir);
const distPackageJson = (0, path_1.resolve)(outDirRelativeToWorkspaceRoot, 'package.json');
// Generate a package.json if option has been set.
if (options.generatePackageJson) {
if (context.projectGraph.nodes[context.projectName].type !== 'app') {
devkit_1.logger.warn((0, devkit_1.stripIndents) `The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.
For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`);
}
const builtPackageJson = (0, js_1.createPackageJson)(context.projectName, context.projectGraph, {
target: context.targetName,
root: context.root,
isProduction: !options.includeDevDependenciesInPackageJson, // By default we remove devDependencies since this is a production build.
skipOverrides: options.skipOverrides,
skipPackageManager: options.skipPackageManager,
});
builtPackageJson.type ??= 'module';
(0, devkit_1.writeJsonFile)(`${outDirRelativeToWorkspaceRoot}/package.json`, builtPackageJson);
const packageManager = (0, devkit_1.detectPackageManager)(context.root);
if (packageManager === 'bun') {
devkit_1.logger.warn('Bun lockfile generation is not supported. The generated package.json will not include a lockfile. Run "bun install" in the output directory after deployment if needed.');
}
else {
const lockFile = (0, js_1.createLockFile)(builtPackageJson, context.projectGraph, packageManager);
(0, fs_1.writeFileSync)(`${outDirRelativeToWorkspaceRoot}/${(0, js_1.getLockFileName)(packageManager)}`, lockFile, {
encoding: 'utf-8',
});
}
}
// For buildable libs, copy package.json if it exists.
else if (options.generatePackageJson !== false &&
!(0, fs_1.existsSync)(distPackageJson) &&
(0, fs_1.existsSync)(libraryPackageJson) &&
rootPackageJson !== libraryPackageJson) {
await (0, js_1.copyAssets)({
outputPath: outDirRelativeToWorkspaceRoot,
assets: [
{
input: projectRoot,
output: '.',
glob: 'package.json',
},
],
}, context);
}
const iterable = (0, async_iterable_1.createAsyncIterable)(({ next, done }) => {
if ('on' in watcherOrOutput) {
let success = true;
watcherOrOutput.on('event', (event) => {
if (event.code === 'START') {
success = true;
}
else if (event.code === 'ERROR') {
success = false;
}
else if (event.code === 'END') {
next({ success });
}
// result must be closed when present.
// see https://rollupjs.org/guide/en/#rollupwatch
if ('result' in event && event.result) {
event.result.close();
}
});
}
else {
const output = watcherOrOutput?.['output'] || watcherOrOutput?.[0]?.output;
const fileName = output?.[0]?.fileName || 'main.cjs';
const outfile = (0, path_1.resolve)(outDirRelativeToWorkspaceRoot, fileName);
next({ success: true, outfile });
done();
}
});
iterables.push(iterable);
}
return yield* (0, async_iterable_1.combineAsyncIterables)(iterables.shift(), ...(iterables ?? []));
}
async function getBuildExtraArgs(options) {
// support passing extra args to vite cli
const schema = await Promise.resolve().then(() => __importStar(require('./schema.json')));
const extraArgs = {};
for (const key of Object.keys(options)) {
if (!schema.properties[key]) {
extraArgs[key] = options[key];
}
}
const buildOptions = {};
const buildSchemaKeys = [
'target',
'polyfillModulePreload',
'modulePreload',
'outDir',
'assetsDir',
'assetsInlineLimit',
'cssCodeSplit',
'cssTarget',
'cssMinify',
'sourcemap',
'minify',
'terserOptions',
'rollupOptions',
'rolldownOptions',
'commonjsOptions',
'dynamicImportVarsOptions',
'write',
'emptyOutDir',
'copyPublicDir',
'manifest',
'lib',
'ssr',
'ssrManifest',
'ssrEmitAssets',
'reportCompressedSize',
'chunkSizeWarningLimit',
'watch',
];
const otherOptions = {};
for (const key of Object.keys(extraArgs)) {
if (buildSchemaKeys.includes(key)) {
buildOptions[key] = extraArgs[key];
}
else {
otherOptions[key] = extraArgs[key];
}
}
buildOptions['watch'] = options.watch ?? undefined;
return {
buildOptions,
otherOptions,
};
}
exports.default = viteBuildExecutor;

View File

@@ -0,0 +1,3 @@
declare const _default: any;
export default _default;
//# sourceMappingURL=compat.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/build/compat.ts"],"names":[],"mappings":";AAGA,wBAAoD"}

6
node_modules/@nx/vite/src/executors/build/compat.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const build_impl_1 = tslib_1.__importDefault(require("./build.impl"));
exports.default = (0, devkit_1.convertNxExecutor)(build_impl_1.default);

13
node_modules/@nx/vite/src/executors/build/schema.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
export interface ViteBuildExecutorOptions {
buildLibsFromSource?: boolean;
configFile?: string;
generatePackageJson?: boolean;
includeDevDependenciesInPackageJson?: boolean;
outputPath?: string;
skipOverrides?: boolean;
skipPackageManager?: boolean;
skipTypeCheck?: boolean;
tsConfig?: string;
watch?: boolean;
useEnvironmentsApi?: boolean;
}

81
node_modules/@nx/vite/src/executors/build/schema.json generated vendored Normal file
View File

@@ -0,0 +1,81 @@
{
"version": 2,
"outputCapture": "direct-nodejs",
"title": "Vite Prod Builder",
"cli": "nx",
"description": "Builds a Vite application for production.",
"type": "object",
"presets": [
{
"name": "Default minimum setup",
"keys": []
}
],
"properties": {
"outputPath": {
"type": "string",
"description": "The output path of the generated files.",
"x-completion-type": "directory",
"x-priority": "important"
},
"buildLibsFromSource": {
"type": "boolean",
"description": "Read buildable libraries from source instead of building them separately.",
"default": true
},
"skipTypeCheck": {
"type": "boolean",
"description": "Skip type-checking via TypeScript. Skipping type-checking speeds up the build but type errors are not caught.",
"default": false
},
"tsConfig": {
"type": "string",
"description": "The path to custom tsconfig file for type-checking when skipTypeCheck is false. Required when tsconfig file is not at the projectRoot level.",
"x-completion-type": "file",
"x-completion-glob": "tsconfig.*.json"
},
"configFile": {
"type": "string",
"description": "The name of the Vite configuration file.",
"x-completion-type": "file",
"x-completion-glob": "vite.config.@(js|ts)"
},
"watch": {
"description": "Enable re-building when files change.",
"oneOf": [
{
"type": "boolean"
},
{
"type": "object"
}
],
"default": false
},
"generatePackageJson": {
"description": "Generate a package.json for the build output.",
"type": "boolean"
},
"includeDevDependenciesInPackageJson": {
"description": "Include devDependencies in the generated package.json.",
"type": "boolean"
},
"skipOverrides": {
"type": "boolean",
"description": "Do not add a `overrides` and `resolutions` entries to the generated package.json file. Only works in conjunction with `generatePackageJson` option."
},
"skipPackageManager": {
"type": "boolean",
"description": "Do not add a `packageManager` entry to the generated package.json file. Only works in conjunction with `generatePackageJson` option."
},
"useEnvironmentsApi": {
"alias": "app",
"type": "boolean",
"description": "Use the new Environments API for building multiple environments at once. Only works with Vite 6.0.0 or higher.",
"default": false
}
},
"definitions": {},
"required": [],
"examplesFile": "../../../docs/build-examples.md"
}

View File

@@ -0,0 +1,3 @@
declare const _default: any;
export default _default;
//# sourceMappingURL=compat.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/dev-server/compat.ts"],"names":[],"mappings":";AAGA,wBAAwD"}

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const dev_server_impl_1 = tslib_1.__importDefault(require("./dev-server.impl"));
exports.default = (0, devkit_1.convertNxExecutor)(dev_server_impl_1.default);

View File

@@ -0,0 +1,8 @@
import { ExecutorContext } from '@nx/devkit';
import { ViteDevServerExecutorOptions } from './schema';
export declare function viteDevServerExecutor(options: ViteDevServerExecutorOptions, context: ExecutorContext): AsyncGenerator<{
success: boolean;
baseUrl: string;
}>;
export default viteDevServerExecutor;
//# sourceMappingURL=dev-server.impl.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"dev-server.impl.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/dev-server/dev-server.impl.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAGhB,MAAM,YAAY,CAAC;AAMpB,OAAO,EAAE,4BAA4B,EAAE,MAAM,UAAU,CAAC;AASxD,wBAAuB,qBAAqB,CAC1C,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,eAAe,GACvB,cAAc,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CA0FvD;AAiBD,eAAe,qBAAqB,CAAC"}

View File

@@ -0,0 +1,163 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.viteDevServerExecutor = viteDevServerExecutor;
const devkit_1 = require("@nx/devkit");
const options_utils_1 = require("../../utils/options-utils");
const executor_utils_1 = require("../../utils/executor-utils");
const path_1 = require("path");
const build_impl_1 = require("../build/build.impl");
async function* viteDevServerExecutor(options, context) {
process.env.VITE_CJS_IGNORE_WARNING = 'true';
// Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
const { mergeConfig, createServer, resolveConfig } = await (0, executor_utils_1.loadViteDynamicImport)();
const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
const root = projectRoot === '.'
? process.cwd()
: (0, path_1.relative)(context.cwd, (0, devkit_1.joinPathFragments)(context.root, projectRoot));
(0, executor_utils_1.createBuildableTsConfig)(projectRoot, options, context);
// Retrieve the option for the configured buildTarget.
const buildTargetOptions = (0, options_utils_1.getNxTargetOptions)(options.buildTarget, context);
const { configuration } = (0, devkit_1.parseTargetString)(options.buildTarget, context);
const { buildOptions, otherOptions: otherOptionsFromBuild } = await (0, build_impl_1.getBuildExtraArgs)(buildTargetOptions);
const viteConfigPath = (0, options_utils_1.normalizeViteConfigFilePath)(context.root, projectRoot, buildTargetOptions.configFile);
const { serverOptions, otherOptions } = await getServerExtraArgs(options, configuration, buildOptions, otherOptionsFromBuild);
const defaultMode = otherOptions?.mode ?? buildTargetOptions?.['mode'] ?? 'development';
const resolved = await resolveConfig({
configFile: viteConfigPath,
mode: defaultMode,
}, 'serve', defaultMode, process.env.NODE_ENV ?? defaultMode);
// vite InlineConfig
const serverConfig = mergeConfig({
// This should not be needed as it's going to be set in vite.config.ts
// but leaving it here in case someone did not migrate correctly
root: resolved.root ?? root,
configFile: viteConfigPath,
}, {
server: {
...(await (0, options_utils_1.getViteServerOptions)(options, context)),
...serverOptions,
},
...otherOptions,
});
try {
const server = await createServer(serverConfig);
await runViteDevServer(server);
const resolvedUrls = [
...server.resolvedUrls.local,
...server.resolvedUrls.network,
];
yield {
success: true,
baseUrl: resolvedUrls[0] ?? '',
};
}
catch (e) {
console.error(e);
yield {
success: false,
baseUrl: '',
};
}
await new Promise((resolve) => {
process.once('SIGINT', () => resolve());
process.once('SIGTERM', () => resolve());
process.once('exit', () => resolve());
});
}
// vite ViteDevServer
async function runViteDevServer(server) {
await server.listen();
server.printUrls();
const processOnExit = async () => {
await server.close();
};
process.once('SIGINT', processOnExit);
process.once('SIGTERM', processOnExit);
process.once('exit', processOnExit);
}
exports.default = viteDevServerExecutor;
async function getServerExtraArgs(options, configuration, buildOptionsFromBuildTarget, otherOptionsFromBuildTarget) {
// support passing extra args to vite cli
const schema = await Promise.resolve().then(() => __importStar(require('./schema.json')));
const extraArgs = {};
for (const key of Object.keys(options)) {
if (!schema.properties[key]) {
extraArgs[key] = options[key];
}
}
let serverOptions = {};
const serverSchemaKeys = [
'hmr',
'warmup',
'watch',
'middlewareMode',
'fs',
'origin',
'preTransformRequests',
'sourcemapIgnoreList',
'port',
'strictPort',
'host',
'https',
'open',
'proxy',
'cors',
'headers',
];
let otherOptions = {};
for (const key of Object.keys(extraArgs)) {
if (serverSchemaKeys.includes(key)) {
serverOptions[key] = extraArgs[key];
}
else {
otherOptions[key] = extraArgs[key];
}
}
if (configuration) {
serverOptions = {
...serverOptions,
watch: buildOptionsFromBuildTarget?.watch ?? serverOptions?.watch,
};
otherOptions = {
...otherOptions,
...(otherOptionsFromBuildTarget ?? {}),
};
}
return {
serverOptions,
otherOptions,
};
}

View File

@@ -0,0 +1,5 @@
export interface ViteDevServerExecutorOptions {
buildTarget: string;
buildLibsFromSource?: boolean;
proxyConfig?: string;
}

View File

@@ -0,0 +1,39 @@
{
"version": 2,
"continuous": true,
"outputCapture": "direct-nodejs",
"title": "Vite Dev Server",
"cli": "nx",
"description": "Starts a dev server using Vite.",
"type": "object",
"presets": [
{
"name": "Default minimum setup",
"keys": ["buildTarget"]
},
{
"name": "Using a Different Port",
"keys": ["buildTarget", "port"]
}
],
"properties": {
"buildTarget": {
"type": "string",
"description": "Target which builds the application. Only used to retrieve the configuration as the dev-server does not build the code.",
"x-priority": "important"
},
"buildLibsFromSource": {
"type": "boolean",
"description": "Read buildable libraries from source instead of building them separately.",
"default": true
},
"proxyConfig": {
"type": "string",
"description": "Path to the proxy configuration file.",
"x-completion-type": "file"
}
},
"definitions": {},
"required": ["buildTarget"],
"examplesFile": "../../../docs/dev-server-examples.md"
}

View File

@@ -0,0 +1,3 @@
declare const _default: any;
export default _default;
//# sourceMappingURL=compat.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/preview-server/compat.ts"],"names":[],"mappings":";AAGA,wBAA4D"}

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const preview_server_impl_1 = tslib_1.__importDefault(require("./preview-server.impl"));
exports.default = (0, devkit_1.convertNxExecutor)(preview_server_impl_1.default);

View File

@@ -0,0 +1,8 @@
import { ExecutorContext } from '@nx/devkit';
import { VitePreviewServerExecutorOptions } from './schema';
export declare function vitePreviewServerExecutor(options: VitePreviewServerExecutorOptions, context: ExecutorContext): AsyncGenerator<{
success: boolean;
baseUrl: any;
}, void, unknown>;
export default vitePreviewServerExecutor;
//# sourceMappingURL=preview-server.impl.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"preview-server.impl.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/preview-server/preview-server.impl.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAKhB,MAAM,YAAY,CAAC;AAOpB,OAAO,EAAE,gCAAgC,EAAE,MAAM,UAAU,CAAC;AAK5D,wBAAuB,yBAAyB,CAC9C,OAAO,EAAE,gCAAgC,EACzC,OAAO,EAAE,eAAe;;;kBAsKzB;AAoBD,eAAe,yBAAyB,CAAC"}

View File

@@ -0,0 +1,214 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.vitePreviewServerExecutor = vitePreviewServerExecutor;
const devkit_1 = require("@nx/devkit");
const options_utils_1 = require("../../utils/options-utils");
const path_1 = require("path");
const build_impl_1 = require("../build/build.impl");
const executor_utils_1 = require("../../utils/executor-utils");
async function* vitePreviewServerExecutor(options, context) {
process.env.VITE_CJS_IGNORE_WARNING = 'true';
// Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
const { mergeConfig, preview, resolveConfig } = await (0, executor_utils_1.loadViteDynamicImport)();
const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
const target = (0, devkit_1.parseTargetString)(options.buildTarget, context);
const targetConfiguration = context.projectsConfigurations.projects[target.project]?.targets[target.target];
if (!targetConfiguration) {
throw new Error(`Invalid buildTarget: ${options.buildTarget}`);
}
const isCustomBuildTarget = targetConfiguration.executor !== '@nx/vite:build' &&
targetConfiguration.executor !== '@nrwl/vite:build';
// Retrieve the option for the configured buildTarget.
const buildTargetOptions = (0, options_utils_1.getNxTargetOptions)(options.buildTarget, context);
const { configuration } = (0, devkit_1.parseTargetString)(options.buildTarget, context);
const viteConfigPath = (0, options_utils_1.normalizeViteConfigFilePath)(context.root, projectRoot, buildTargetOptions.configFile);
const { buildOptions, otherOptions: otherOptionsFromBuild } = await (0, build_impl_1.getBuildExtraArgs)({
...buildTargetOptions,
...{
// Enable watch mode by default for the build target.
watch: options.watch ?? true,
},
});
const { previewOptions, otherOptions } = await getExtraArgs(options, configuration, otherOptionsFromBuild);
const defaultMode = otherOptions?.mode ?? otherOptionsFromBuild?.mode ?? 'production';
const resolved = await resolveConfig({
configFile: viteConfigPath,
mode: defaultMode,
}, 'build', defaultMode, process.env.NODE_ENV ?? defaultMode, true);
const outDir = options.staticFilePath ??
(0, devkit_1.joinPathFragments)((0, devkit_1.offsetFromRoot)(projectRoot), buildTargetOptions.outputPath) ??
resolved?.build?.outDir;
if (!outDir) {
throw new Error(`Could not infer the "outputPath" or "outDir". It should be set in your vite.config.ts, or as a property of the "${options.buildTarget}" buildTarget or provided explicitly as a "staticFilePath" option.`);
}
const root = projectRoot === '.'
? process.cwd()
: (0, path_1.relative)(context.cwd, (0, devkit_1.joinPathFragments)(context.root, projectRoot));
// Merge the options from the build and preview-serve targets.
// The latter takes precedence.
const mergedOptions = {
...{ watch: {} },
build: {
outDir,
...(isCustomBuildTarget ? {} : buildOptions),
},
...(isCustomBuildTarget ? {} : otherOptionsFromBuild),
...otherOptions,
preview: {
...(0, options_utils_1.getProxyConfig)(context, otherOptions.proxyConfig),
...previewOptions,
},
};
// vite InlineConfig
const serverConfig = mergeConfig({
// This should not be needed as it's going to be set in vite.config.ts
// but leaving it here in case someone did not migrate correctly
root: resolved.root ?? root,
configFile: viteConfigPath,
}, {
...mergedOptions,
});
if (serverConfig.mode === 'production') {
console.warn('WARNING: preview is not meant to be run in production!');
}
// vite PreviewServer
let server;
const processOnExit = async () => {
await closeServer(server);
};
process.once('SIGINT', processOnExit);
process.once('SIGTERM', processOnExit);
process.once('exit', processOnExit);
// Launch the build target.
// If customBuildTarget is set to true, do not provide any overrides to it
const buildTargetOverrides = isCustomBuildTarget ? {} : mergedOptions;
const build = await (0, devkit_1.runExecutor)(target, buildTargetOverrides, context);
for await (const result of build) {
if (result.success) {
try {
if (!server) {
server = await preview(serverConfig);
}
server.printUrls();
const resolvedUrls = [
...server.resolvedUrls.local,
...server.resolvedUrls.network,
];
yield {
success: true,
baseUrl: resolvedUrls[0] ?? '',
};
}
catch (e) {
console.error(e);
yield {
success: false,
baseUrl: '',
};
}
}
else {
yield {
success: false,
baseUrl: '',
};
}
}
await new Promise((resolve) => {
process.once('SIGINT', () => resolve());
process.once('SIGTERM', () => resolve());
process.once('exit', () => resolve());
});
}
function closeServer(server) {
return new Promise((resolve) => {
if (!server) {
resolve();
}
else {
const { httpServer } = server;
if (httpServer['closeAllConnections']) {
// https://github.com/vitejs/vite/pull/14834
// closeAllConnections was added in Node v18.2.0
// typically is "as http.Server" but no reason
// to import http just for this
httpServer.closeAllConnections();
}
httpServer.close(() => resolve());
}
});
}
exports.default = vitePreviewServerExecutor;
async function getExtraArgs(options, configuration, otherOptionsFromBuildTarget) {
// support passing extra args to vite cli
const schema = await Promise.resolve().then(() => __importStar(require('./schema.json')));
const extraArgs = {};
for (const key of Object.keys(options)) {
if (!schema.properties[key]) {
extraArgs[key] = options[key];
}
}
const previewOptions = {};
const previewSchemaKeys = [
'port',
'strictPort',
'host',
'https',
'open',
'proxy',
'cors',
'headers',
];
let otherOptions = {};
for (const key of Object.keys(extraArgs)) {
if (previewSchemaKeys.includes(key)) {
previewOptions[key] = extraArgs[key];
}
else {
otherOptions[key] = extraArgs[key];
}
}
if (configuration) {
otherOptions = {
...otherOptions,
...(otherOptionsFromBuildTarget ?? {}),
};
}
return {
previewOptions,
otherOptions,
};
}

View File

@@ -0,0 +1,6 @@
export interface VitePreviewServerExecutorOptions {
buildTarget: string;
proxyConfig?: string;
staticFilePath?: string;
watch?: boolean;
}

View File

@@ -0,0 +1,43 @@
{
"$schema": "https://json-schema.org/schema",
"version": 2,
"cli": "nx",
"title": "Vite Preview Server",
"description": "Preview Server for Vite.",
"continuous": true,
"type": "object",
"presets": [
{
"name": "Default minimum setup",
"keys": ["buildTarget"]
},
{
"name": "Using a Different Port",
"keys": ["buildTarget", "port"]
}
],
"properties": {
"buildTarget": {
"type": "string",
"description": "Target which builds the application."
},
"proxyConfig": {
"type": "string",
"description": "Path to the proxy configuration file.",
"x-completion-type": "file"
},
"staticFilePath": {
"type": "string",
"description": "Path where the build artifacts are located. If not provided then it will be infered from the buildTarget executor options as outputPath",
"x-completion-type": "directory"
},
"watch": {
"type": "boolean",
"description": "Enable re-building when files change. If not specified, watch mode will be enabled by default.",
"default": true
}
},
"definitions": {},
"required": ["buildTarget"],
"examplesFile": "../../../docs/preview-server-examples.md"
}

3
node_modules/@nx/vite/src/executors/test/compat.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
declare const _default: any;
export default _default;
//# sourceMappingURL=compat.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/test/compat.ts"],"names":[],"mappings":";AAGA,wBAAiD"}

6
node_modules/@nx/vite/src/executors/test/compat.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const vitest_impl_1 = tslib_1.__importDefault(require("./vitest.impl"));
exports.default = (0, devkit_1.convertNxExecutor)(vitest_impl_1.default);

View File

@@ -0,0 +1,19 @@
import type { RunnerTestFile, Reporter } from 'vitest/node';
export declare class NxReporter implements Reporter {
private watch;
deferred: {
promise: Promise<boolean>;
resolve: (val: boolean) => void;
};
constructor(watch: boolean);
[Symbol.asyncIterator](): AsyncGenerator<{
hasErrors: boolean;
}, void, unknown>;
private setupDeferred;
/** Vitest ≥ 0.29 */
onTestRunEnd(files: any[], errors?: any): void;
/** Vitest ≤ 0.28 */
onFinished(files: RunnerTestFile[], errors?: unknown[]): void;
private _handleFinished;
}
//# sourceMappingURL=nx-reporter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nx-reporter.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/executors/test/lib/nx-reporter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE5D,qBAAa,UAAW,YAAW,QAAQ;IAM7B,OAAO,CAAC,KAAK;IALzB,QAAQ,EAAE;QACR,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QAC1B,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;KACjC,CAAC;gBAEkB,KAAK,EAAE,OAAO;IAI3B,CAAC,MAAM,CAAC,aAAa,CAAC;;;IAQ7B,OAAO,CAAC,aAAa;IAUrB,oBAAoB;IACpB,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,MAAM,CAAC,EAAE,GAAG;IAIvC,oBAAoB;IACpB,UAAU,CAAC,KAAK,EAAE,cAAc,EAAE,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE;IAKtD,OAAO,CAAC,eAAe;CAKxB"}

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NxReporter = void 0;
class NxReporter {
constructor(watch) {
this.watch = watch;
this.setupDeferred();
}
async *[Symbol.asyncIterator]() {
do {
const hasErrors = await this.deferred.promise;
yield { hasErrors };
this.setupDeferred();
} while (this.watch);
}
setupDeferred() {
let resolve;
this.deferred = {
promise: new Promise((res) => {
resolve = res;
}),
resolve,
};
}
/** Vitest ≥ 0.29 */
onTestRunEnd(files, errors) {
this._handleFinished(files, errors);
}
/** Vitest ≤ 0.28 */
onFinished(files, errors) {
this._handleFinished(files, errors);
}
// --- private ----------------------------------------------------------
_handleFinished(files, errors) {
const hasErrors = files.some((f) => f.result?.state === 'fail') || errors?.length > 0;
this.deferred.resolve(hasErrors);
}
}
exports.NxReporter = NxReporter;

View File

@@ -0,0 +1,5 @@
import { ExecutorContext } from '@nx/devkit';
import { VitestExecutorOptions } from '../schema';
export declare function getOptions(options: VitestExecutorOptions, context: ExecutorContext, projectRoot: string): Promise<Record<string, any>>;
export declare function getOptionsAsArgv(obj: Record<string, any>): string[];
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/executors/test/lib/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAIhB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAQlD,wBAAsB,UAAU,CAC9B,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,eAAe,EACxB,WAAW,EAAE,MAAM,gCAuEpB;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,EAAE,CAcnE"}

68
node_modules/@nx/vite/src/executors/test/lib/utils.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOptions = getOptions;
exports.getOptionsAsArgv = getOptionsAsArgv;
const devkit_1 = require("@nx/devkit");
const options_utils_1 = require("../../../utils/options-utils");
const path_1 = require("path");
const executor_utils_1 = require("../../../utils/executor-utils");
async function getOptions(options, context, projectRoot) {
// Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
const { loadConfigFromFile, mergeConfig } = await (0, executor_utils_1.loadViteDynamicImport)();
const viteConfigPath = (0, options_utils_1.normalizeViteConfigFilePath)(context.root, projectRoot, options.configFile);
if (!viteConfigPath) {
throw new Error((0, devkit_1.stripIndents) `
Unable to load test config from config file ${viteConfigPath}.
Please make sure that vitest is configured correctly,
or use the @nx/vite:vitest generator to configure it for you.
You can read more here: https://nx.dev/nx-api/vite/generators/vitest
`);
}
const resolved = await loadConfigFromFile({
mode: options?.mode ?? 'production',
command: 'serve',
}, viteConfigPath);
if (!viteConfigPath || !resolved?.config?.['test']) {
devkit_1.logger.warn((0, devkit_1.stripIndents) `Unable to load test config from config file ${resolved?.path ?? viteConfigPath}
Some settings may not be applied as expected.
You can manually set the config in the project, ${context.projectName}, configuration.
`);
}
const root = projectRoot === '.'
? process.cwd()
: (0, path_1.relative)(context.cwd, (0, devkit_1.joinPathFragments)(context.root, projectRoot));
const { parseCLI } = await (0, executor_utils_1.loadVitestDynamicImport)();
const { options: { watch, ...normalizedExtraArgs }, } = parseCLI(['vitest', ...getOptionsAsArgv(options)]);
const { reportsDirectory, coverage, ...restNormalizedArgs } = normalizedExtraArgs;
const settings = {
// Explicitly set watch mode to false if not provided otherwise vitest
// will enable watch mode by default for non CI environments
watch: watch ?? false,
...restNormalizedArgs,
// This should not be needed as it's going to be set in vite.config.ts
// but leaving it here in case someone did not migrate correctly
root: resolved.config.root ?? root,
config: viteConfigPath,
coverage: {
...(coverage ?? {}),
...(reportsDirectory && { reportsDirectory }),
},
};
return mergeConfig(resolved?.config?.['test'] ?? {}, settings);
}
function getOptionsAsArgv(obj) {
const argv = [];
for (const [key, value] of Object.entries(obj)) {
if (Array.isArray(value)) {
value.forEach((item) => argv.push(`--${key}=${item}`));
}
else if (typeof value === 'object' && value !== null) {
argv.push(`--${key}='${JSON.stringify(value)}'`);
}
else {
argv.push(`--${key}=${value}`);
}
}
return argv;
}

7
node_modules/@nx/vite/src/executors/test/schema.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export interface VitestExecutorOptions {
configFile?: string;
reportsDirectory?: string;
testFiles?: string[];
watch?: boolean;
mode?: string;
}

36
node_modules/@nx/vite/src/executors/test/schema.json generated vendored Normal file
View File

@@ -0,0 +1,36 @@
{
"$schema": "https://json-schema.org/schema",
"version": 2,
"cli": "nx",
"title": "Vitest executor",
"description": "Test using Vitest.",
"type": "object",
"properties": {
"configFile": {
"type": "string",
"description": "The path to the local vitest config, relative to the workspace root.",
"x-completion-type": "file",
"x-completion-glob": "@(vitest|vite).config@(.js|.ts)",
"aliases": ["config"]
},
"reportsDirectory": {
"type": "string",
"description": "Directory to write coverage report to."
},
"mode": {
"type": "string",
"description": "Mode for Vite."
},
"testFiles": {
"aliases": ["testFile"],
"type": "array",
"items": { "type": "string" }
},
"watch": {
"description": "Watch files for changes and rerun tests related to changed files.",
"type": "boolean"
}
},
"required": [],
"examplesFile": "../../../docs/test-examples.md"
}

View File

@@ -0,0 +1,10 @@
import { ExecutorContext } from '@nx/devkit';
import { VitestExecutorOptions } from './schema';
/**
* @deprecated Use `@nx/vitest:test` instead. This executor will be removed in Nx 23.
*/
export declare function vitestExecutor(options: VitestExecutorOptions, context: ExecutorContext): AsyncGenerator<never, {
success: boolean;
}, unknown>;
export default vitestExecutor;
//# sourceMappingURL=vitest.impl.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"vitest.impl.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/executors/test/vitest.impl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAU,MAAM,YAAY,CAAC;AAGrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD;;GAEG;AACH,wBAAuB,cAAc,CACnC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,eAAe;;YAYzB;AAED,eAAe,cAAc,CAAC"}

View File

@@ -0,0 +1,49 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.vitestExecutor = vitestExecutor;
const devkit_1 = require("@nx/devkit");
const devkit_2 = require("@nx/devkit");
const versions_1 = require("../../utils/versions");
/**
* @deprecated Use `@nx/vitest:test` instead. This executor will be removed in Nx 23.
*/
async function* vitestExecutor(options, context) {
devkit_1.logger.warn(`The '@nx/vite:test' executor is deprecated. Please use '@nx/vitest:test' instead. This executor will be removed in Nx 23.`);
(0, devkit_2.ensurePackage)('@nx/vitest', versions_1.nxVersion);
const { vitestExecutor: actualVitestExecutor } = await Promise.resolve().then(() => __importStar(require('@nx/vitest/executors')));
return yield* actualVitestExecutor(options, context);
}
exports.default = vitestExecutor;

View File

@@ -0,0 +1,6 @@
import { GeneratorCallback, Tree } from '@nx/devkit';
import { ViteConfigurationGeneratorSchema } from './schema';
export declare function viteConfigurationGenerator(host: Tree, schema: ViteConfigurationGeneratorSchema): Promise<GeneratorCallback>;
export declare function viteConfigurationGeneratorInternal(tree: Tree, schema: ViteConfigurationGeneratorSchema): Promise<GeneratorCallback>;
export default viteConfigurationGenerator;
//# sourceMappingURL=configuration.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"configuration.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/generators/configuration/configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,EAMjB,IAAI,EAGL,MAAM,YAAY,CAAC;AAwBpB,OAAO,EAAE,gCAAgC,EAAE,MAAM,UAAU,CAAC;AAE5D,wBAAgB,0BAA0B,CACxC,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,gCAAgC,8BAMzC;AAED,wBAAsB,kCAAkC,CACtD,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,gCAAgC,8BAwJzC;AAED,eAAe,0BAA0B,CAAC"}

View File

@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.viteConfigurationGenerator = viteConfigurationGenerator;
exports.viteConfigurationGeneratorInternal = viteConfigurationGeneratorInternal;
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const js_1 = require("@nx/js");
const get_import_path_1 = require("@nx/js/src/utils/get-import-path");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
const posix_1 = require("node:path/posix");
const ensure_dependencies_1 = require("../../utils/ensure-dependencies");
const generator_utils_1 = require("../../utils/generator-utils");
const init_1 = tslib_1.__importDefault(require("../init/init"));
const vitest_generator_1 = tslib_1.__importDefault(require("../vitest/vitest-generator"));
const convert_non_vite_1 = require("./lib/convert-non-vite");
function viteConfigurationGenerator(host, schema) {
return viteConfigurationGeneratorInternal(host, {
addPlugin: false,
...schema,
});
}
async function viteConfigurationGeneratorInternal(tree, schema) {
const tasks = [];
const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, schema.project);
const { targets, root: projectRoot } = projectConfig;
const projectType = (0, ts_solution_setup_1.getProjectType)(tree, projectConfig.root, schema.projectType ?? projectConfig.projectType);
schema.includeLib ??= projectType === 'library';
// Setting default to jsdom since it is the most common use case (React, Web).
// The @nx/js:lib generator specifically sets this to node to be more generic.
schema.testEnvironment ??= 'jsdom';
/**
* This is for when we are converting an existing project
* to use the vite executors.
*/
let projectAlreadyHasViteTargets = {};
if (!schema.newProject) {
await (0, convert_non_vite_1.convertNonVite)(tree, schema, projectRoot, projectType, targets);
}
const jsInitTask = await (0, js_1.initGenerator)(tree, {
...schema,
skipFormat: true,
tsConfigName: projectRoot === '.' ? 'tsconfig.json' : 'tsconfig.base.json',
});
tasks.push(jsInitTask);
const initTask = await (0, init_1.default)(tree, {
...schema,
projectRoot,
skipFormat: true,
});
tasks.push(initTask);
tasks.push((0, ensure_dependencies_1.ensureDependencies)(tree, schema));
const nxJson = (0, devkit_1.readNxJson)(tree);
const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
nxJson.useInferencePlugins !== false;
schema.addPlugin ??= addPluginDefault;
const hasPlugin = nxJson.plugins?.some((p) => typeof p === 'string'
? p === '@nx/vite/plugin'
: p.plugin === '@nx/vite/plugin');
if (!hasPlugin) {
if (!projectAlreadyHasViteTargets.build) {
(0, generator_utils_1.addBuildTarget)(tree, schema, 'build');
}
if (!schema.includeLib) {
if (!projectAlreadyHasViteTargets.serve) {
(0, generator_utils_1.addServeTarget)(tree, schema, 'serve');
}
if (!projectAlreadyHasViteTargets.preview) {
(0, generator_utils_1.addPreviewTarget)(tree, schema, 'preview');
}
}
}
if (projectType === 'library') {
// update tsconfig.lib.json to include vite/client
(0, devkit_1.updateJson)(tree, (0, devkit_1.joinPathFragments)(projectRoot, 'tsconfig.lib.json'), (json) => {
json.compilerOptions ??= {};
json.compilerOptions.types ??= [];
if (!json.compilerOptions.types.includes('vite/client')) {
json.compilerOptions.types.push('vite/client');
}
return json;
});
}
if (!schema.newProject) {
// We are converting existing project to use Vite
if (schema.uiFramework === 'react') {
(0, generator_utils_1.createOrEditViteConfig)(tree, {
project: schema.project,
includeLib: schema.includeLib,
includeVitest: schema.includeVitest,
inSourceTests: schema.inSourceTests,
rollupOptionsExternal: [
"'react'",
"'react-dom'",
"'react/jsx-runtime'",
],
imports: [
schema.compiler === 'swc'
? `import react from '@vitejs/plugin-react-swc'`
: `import react from '@vitejs/plugin-react'`,
],
plugins: ['react()'],
port: schema.port,
useEsmExtension: true,
}, false, undefined);
}
else {
(0, generator_utils_1.createOrEditViteConfig)(tree, { ...schema, useEsmExtension: true }, false, projectAlreadyHasViteTargets);
}
}
if (schema.includeVitest) {
const vitestTask = await (0, vitest_generator_1.default)(tree, {
project: schema.project,
uiFramework: schema.uiFramework,
inSourceTests: schema.inSourceTests,
coverageProvider: 'v8',
skipViteConfig: true,
testTarget: 'test',
skipFormat: true,
addPlugin: schema.addPlugin,
compiler: schema.compiler,
projectType,
}, false, true);
tasks.push(vitestTask);
}
if ((0, ts_solution_setup_1.isUsingTsSolutionSetup)(tree)) {
updatePackageJson(tree, schema, projectType);
}
if (!schema.skipFormat) {
await (0, devkit_1.formatFiles)(tree);
}
return (0, devkit_1.runTasksInSerial)(...tasks);
}
exports.default = viteConfigurationGenerator;
function updatePackageJson(tree, options, projectType) {
const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
const packageJsonPath = (0, posix_1.join)(project.root, 'package.json');
let packageJson;
if (tree.exists(packageJsonPath)) {
packageJson = (0, devkit_1.readJson)(tree, packageJsonPath);
}
else {
packageJson = {
name: (0, get_import_path_1.getImportPath)(tree, options.project),
version: '0.0.1',
};
if ((0, ts_solution_setup_1.getProjectType)(tree, project.root, projectType) === 'application') {
packageJson.private = true;
}
}
if (projectType === 'library') {
// we always write/override the vite and project config with some set values,
// so we can rely on them
const main = (0, posix_1.join)(project.root, 'src/index.ts');
// we configure the dts plugin with the entryRoot set to `src`
const rootDir = (0, posix_1.join)(project.root, 'src');
const outputPath = (0, devkit_1.joinPathFragments)(project.root, 'dist');
packageJson = (0, js_1.getUpdatedPackageJsonContent)(packageJson, {
main,
outputPath,
projectRoot: project.root,
rootDir,
generateExportsField: true,
packageJsonPath,
format: ['esm'],
developmentConditionName: (0, ts_solution_setup_1.getDefinedCustomConditionName)(tree),
});
}
(0, devkit_1.writeJson)(tree, packageJsonPath, packageJson);
}

View File

@@ -0,0 +1,6 @@
import { TargetConfiguration, Tree } from '@nx/devkit';
import { ViteConfigurationGeneratorSchema } from '../schema';
export declare function convertNonVite(tree: Tree, schema: ViteConfigurationGeneratorSchema, projectRoot: string, _projectType: string, targets: {
[targetName: string]: TargetConfiguration<any>;
}): Promise<void>;
//# sourceMappingURL=convert-non-vite.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"convert-non-vite.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/configuration/lib/convert-non-vite.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,IAAI,EAGL,MAAM,YAAY,CAAC;AAKpB,OAAO,EAAE,gCAAgC,EAAE,MAAM,WAAW,CAAC;AAU7D,wBAAsB,cAAc,CAClC,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,gCAAgC,EACxC,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE;IACP,CAAC,UAAU,EAAE,MAAM,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;CAChD,iBA8EF"}

View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertNonVite = convertNonVite;
const devkit_1 = require("@nx/devkit");
const find_vite_config_1 = require("../../../utils/find-vite-config");
const generator_utils_1 = require("../../../utils/generator-utils");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
async function convertNonVite(tree, schema, projectRoot, _projectType, targets) {
// Check if it has vite
const hasViteConfig = (0, find_vite_config_1.findViteConfig)(tree, projectRoot);
const hasIndexHtmlAtRoot = tree.exists((0, devkit_1.joinPathFragments)(projectRoot, 'index.html'));
// Check if it has webpack
const hasWebpackConfig = (0, find_vite_config_1.findWebpackConfig)(tree, projectRoot);
const projectType = (0, ts_solution_setup_1.getProjectType)(tree, projectRoot, _projectType);
if (hasWebpackConfig) {
if (projectType === 'application') {
(0, generator_utils_1.moveAndEditIndexHtml)(tree, schema);
}
(0, generator_utils_1.deleteWebpackConfig)(tree, projectRoot, hasWebpackConfig);
(0, generator_utils_1.editTsConfig)(tree, schema);
return;
}
if (projectType === 'application' &&
hasViteConfig &&
hasIndexHtmlAtRoot &&
!hasWebpackConfig) {
throw new Error(`The project ${schema.project} is already configured to use Vite.`);
return;
}
if (projectType === 'library' && hasViteConfig) {
// continue anyway - it could need to be updated - only update vite.config.ts in any case
(0, generator_utils_1.editTsConfig)(tree, schema);
return;
}
// Does the project have js executors?
const { supported: jsTargetName, unsupported } = (0, generator_utils_1.findExistingJsBuildTargetInProject)(targets);
if (jsTargetName) {
(0, generator_utils_1.editTsConfig)(tree, schema);
return;
}
if (unsupported) {
throw new Error(`
Nx cannot convert your project to use vite.
Please try again with a different project.
`);
}
// If it's a library, it's most possible it's non-buildable
// So fix the tsconfig and return, to continue with the rest of the setup
if (projectType === 'library' &&
!hasViteConfig &&
!hasWebpackConfig &&
!jsTargetName) {
(0, generator_utils_1.editTsConfig)(tree, schema);
return;
}
/**
* The project is an app.
* The project has no js executors, no webpack config, no vite config.
* We did not find any configuration that hints the project can
* definitely be converted.
* So, we should warn the user about it.
* They can choose whether to convert it or not
*/
await (0, generator_utils_1.handleUnknownConfiguration)(schema.project);
}

View File

@@ -0,0 +1,17 @@
export interface ViteConfigurationGeneratorSchema {
uiFramework: 'react' | 'none';
compiler?: 'babel' | 'swc';
project: string;
newProject?: boolean;
includeVitest?: boolean;
inSourceTests?: boolean;
includeLib?: boolean;
skipFormat?: boolean;
testEnvironment?: 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string;
port?: number;
// Internal options
addPlugin?: boolean;
projectType?: 'application' | 'library';
previewPort?: number;
useViteV7?: boolean;
}

View File

@@ -0,0 +1,65 @@
{
"cli": "nx",
"title": "Configure a project to use Vite.",
"description": "Configure a project to use Vite.",
"$id": "configure-vite-project",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "The name of the project.",
"$default": {
"$source": "argv",
"index": 0
},
"aliases": ["name", "projectName"],
"x-dropdown": "project",
"x-prompt": "What is the name of the project to set up Vite for?"
},
"includeLib": {
"type": "boolean",
"description": "Add a library build option and skip the server option.",
"hidden": true
},
"includeVitest": {
"type": "boolean",
"description": "Use vitest for the test suite."
},
"uiFramework": {
"type": "string",
"description": "UI Framework to use for Vite.",
"enum": ["react", "none"],
"default": "none",
"x-prompt": "What UI framework plugin should Vite use?"
},
"compiler": {
"type": "string",
"description": "Compiler to use for Vite when UI Framework is React.",
"enum": ["babel", "swc"],
"default": "babel"
},
"newProject": {
"type": "boolean",
"description": "Is this a new project?",
"default": false,
"hidden": true
},
"skipFormat": {
"description": "Skip formatting files.",
"type": "boolean",
"default": false,
"x-priority": "internal"
},
"testEnvironment": {
"description": "The vitest environment to use. See https://vitest.dev/config/#environment.",
"type": "string",
"enum": ["node", "jsdom", "happy-dom", "edge-runtime"],
"default": "jsdom"
},
"port": {
"type": "number",
"description": "The port to use for the development server"
}
},
"examplesFile": "../../../docs/configuration-examples.md"
}

View File

@@ -0,0 +1,8 @@
import { type Tree } from '@nx/devkit';
interface Schema {
project?: string;
skipFormat?: boolean;
}
export declare function convertToInferred(tree: Tree, options: Schema): Promise<() => void>;
export default convertToInferred;
//# sourceMappingURL=convert-to-inferred.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"convert-to-inferred.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/generators/convert-to-inferred/convert-to-inferred.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwC,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAY7E,UAAU,MAAM;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,uBAqDlE;AAED,eAAe,iBAAiB,CAAC"}

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertToInferred = convertToInferred;
const devkit_1 = require("@nx/devkit");
const executor_to_plugin_migrator_1 = require("@nx/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator");
const plugin_1 = require("../../plugins/plugin");
const build_post_target_transformer_1 = require("./lib/build-post-target-transformer");
const serve_post_target_transformer_1 = require("./lib/serve-post-target-transformer");
const preview_post_target_transformer_1 = require("./lib/preview-post-target-transformer");
const test_post_target_transformer_1 = require("./lib/test-post-target-transformer");
const aggregate_log_util_1 = require("@nx/devkit/src/generators/plugin-migrations/aggregate-log-util");
async function convertToInferred(tree, options) {
const projectGraph = await (0, devkit_1.createProjectGraphAsync)();
const migrationLogs = new aggregate_log_util_1.AggregatedLog();
const migratedProjects = await (0, executor_to_plugin_migrator_1.migrateProjectExecutorsToPlugin)(tree, projectGraph, '@nx/vite/plugin', plugin_1.createNodesV2, {
buildTargetName: 'build',
serveTargetName: 'serve',
previewTargetName: 'preview',
testTargetName: 'test',
serveStaticTargetName: 'serve-static',
}, [
{
executors: ['@nx/vite:build'],
postTargetTransformer: build_post_target_transformer_1.buildPostTargetTransformer,
targetPluginOptionMapper: (target) => ({ buildTargetName: target }),
},
{
executors: ['@nx/vite:dev-server'],
postTargetTransformer: (0, serve_post_target_transformer_1.servePostTargetTransformer)(migrationLogs),
targetPluginOptionMapper: (target) => ({ serveTargetName: target }),
},
{
executors: ['@nx/vite:preview-server'],
postTargetTransformer: (0, preview_post_target_transformer_1.previewPostTargetTransformer)(migrationLogs),
targetPluginOptionMapper: (target) => ({ previewTargetName: target }),
},
{
executors: ['@nx/vite:test'],
postTargetTransformer: test_post_target_transformer_1.testPostTargetTransformer,
targetPluginOptionMapper: (target) => ({ testTargetName: target }),
},
], options.project);
if (migratedProjects.size === 0) {
throw new executor_to_plugin_migrator_1.NoTargetsToMigrateError();
}
if (!options.skipFormat) {
await (0, devkit_1.formatFiles)(tree);
}
return () => {
migrationLogs.flushLogs();
};
}
exports.default = convertToInferred;

View File

@@ -0,0 +1,7 @@
import { type TargetConfiguration, type Tree } from '@nx/devkit';
export declare function buildPostTargetTransformer(target: TargetConfiguration, tree: Tree, projectDetails: {
projectName: string;
root: string;
}, inferredTargetConfiguration: TargetConfiguration): TargetConfiguration<any>;
export declare function moveBuildLibsFromSourceToViteConfig(tree: Tree, configPath: string): void;
//# sourceMappingURL=build-post-target-transformer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"build-post-target-transformer.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/convert-to-inferred/lib/build-post-target-transformer.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAUpB,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,mBAAmB,EAC3B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACrD,2BAA2B,EAAE,mBAAmB,4BAmGjD;AA+CD,wBAAgB,mCAAmC,CACjD,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,MAAM,QA0FnB"}

View File

@@ -0,0 +1,144 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildPostTargetTransformer = buildPostTargetTransformer;
exports.moveBuildLibsFromSourceToViteConfig = moveBuildLibsFromSourceToViteConfig;
const devkit_1 = require("@nx/devkit");
const tsquery_1 = require("@phenomnomnominal/tsquery");
const posix_1 = require("path/posix");
const utils_1 = require("./utils");
const plugin_migration_utils_1 = require("@nx/devkit/src/generators/plugin-migrations/plugin-migration-utils");
function buildPostTargetTransformer(target, tree, projectDetails, inferredTargetConfiguration) {
let viteConfigPath = (0, utils_1.getViteConfigPath)(tree, projectDetails.root);
const configValues = {
default: {},
};
if (target.configurations) {
for (const configurationName in target.configurations) {
const configuration = target.configurations[configurationName];
configValues[configurationName] = {};
let configurationConfigFile = viteConfigPath;
if (configuration.configFile) {
if ('buildLibsFromSource' in target.options) {
configuration.buildLibsFromSource =
target.options.buildLibsFromSource;
}
configurationConfigFile = configuration.configFile;
}
removePropertiesFromTargetOptions(tree, configuration, configurationConfigFile, projectDetails.root, configValues[configurationName], configuration.configFile && configuration.configFile !== viteConfigPath);
}
for (const configurationName in target.configurations) {
const configuration = target.configurations[configurationName];
if (configuration.config &&
configuration.config !==
(0, utils_1.toProjectRelativePath)(viteConfigPath, projectDetails.root)) {
const configFilePath = (0, devkit_1.joinPathFragments)(projectDetails.root, configuration.config);
(0, utils_1.addConfigValuesToViteConfig)(tree, configFilePath, configValues);
}
}
if (Object.keys(target.configurations).length === 0) {
if ('defaultConfiguration' in target) {
delete target.defaultConfiguration;
}
delete target.configurations;
}
if ('defaultConfiguration' in target &&
!target.configurations[target.defaultConfiguration]) {
delete target.defaultConfiguration;
}
}
if (target.options) {
if (target.options.configFile) {
viteConfigPath = target.options.configFile;
}
removePropertiesFromTargetOptions(tree, target.options, viteConfigPath, projectDetails.root, configValues['default'], true);
}
if (target.outputs) {
(0, plugin_migration_utils_1.processTargetOutputs)(target, [{ newName: 'outDir', oldName: 'outputPath' }], inferredTargetConfiguration, {
projectName: projectDetails.projectName,
projectRoot: projectDetails.root,
});
}
if (target.inputs &&
target.inputs.every((i) => i === 'production' || i === '^production')) {
delete target.inputs;
}
(0, utils_1.addConfigValuesToViteConfig)(tree, viteConfigPath, configValues);
return target;
}
function removePropertiesFromTargetOptions(tree, targetOptions, viteConfigPath, projectRoot, configValues, needsAstTransform = false) {
if ('configFile' in targetOptions) {
targetOptions.config = (0, utils_1.toProjectRelativePath)(targetOptions.configFile, projectRoot);
delete targetOptions.configFile;
}
if (targetOptions.outputPath) {
targetOptions.outDir = (0, utils_1.toProjectRelativePath)(targetOptions.outputPath, projectRoot);
delete targetOptions.outputPath;
}
if ('buildLibsFromSource' in targetOptions) {
configValues['buildLibsFromSource'] = targetOptions.buildLibsFromSource;
if (needsAstTransform) {
moveBuildLibsFromSourceToViteConfig(tree, viteConfigPath);
}
delete targetOptions.buildLibsFromSource;
}
if ('skipTypeCheck' in targetOptions) {
delete targetOptions.skipTypeCheck;
}
if ('generatePackageJson' in targetOptions) {
delete targetOptions.generatePackageJson;
}
if ('includeDevDependenciesInPackageJson' in targetOptions) {
delete targetOptions.includeDevDependenciesInPackageJson;
}
if ('tsConfig' in targetOptions) {
delete targetOptions.tsConfig;
}
}
function moveBuildLibsFromSourceToViteConfig(tree, configPath) {
const PLUGINS_PROPERTY_SELECTOR = 'PropertyAssignment:has(Identifier[name=plugins])';
const PLUGINS_NX_VITE_TS_PATHS_SELECTOR = 'PropertyAssignment:has(Identifier[name=plugins]) CallExpression:has(Identifier[name=nxViteTsPaths])';
const BUILD_LIBS_FROM_SOURCE_SELECTOR = 'PropertyAssignment:has(Identifier[name=plugins]) CallExpression:has(Identifier[name=nxViteTsPaths]) ObjectLiteralExpression > PropertyAssignment:has(Identifier[name=buildLibsFromSource])';
const nxViteTsPathsImport = (0, posix_1.extname)(configPath) === 'js'
? 'const {nxViteTsPaths} = require("@nx/vite/plugins/nx-tsconfig-paths.plugin");'
: 'import { nxViteTsPaths } from "@nx/vite/plugins/nx-tsconfig-paths.plugin";';
const plugin = `nxViteTsPaths({ buildLibsFromSource: options.buildLibsFromSource }),`;
const viteConfigContents = tree.read(configPath, 'utf-8');
let newViteConfigContents = viteConfigContents;
const sourceFile = (0, tsquery_1.ast)(viteConfigContents);
const buildLibsFromSourceNodes = (0, tsquery_1.query)(sourceFile, BUILD_LIBS_FROM_SOURCE_SELECTOR);
if (buildLibsFromSourceNodes.length > 0) {
return;
}
const nxViteTsPathsNodes = (0, tsquery_1.query)(sourceFile, PLUGINS_NX_VITE_TS_PATHS_SELECTOR);
if (nxViteTsPathsNodes.length === 0) {
const pluginsNodes = (0, tsquery_1.query)(sourceFile, PLUGINS_PROPERTY_SELECTOR);
if (pluginsNodes.length === 0) {
// Add plugin property
const configNodes = (0, tsquery_1.query)(sourceFile, 'CallExpression:has(Identifier[name=defineConfig]) > ObjectLiteralExpression');
if (configNodes.length === 0) {
return;
}
newViteConfigContents = `${nxViteTsPathsImport}\n${viteConfigContents.slice(0, configNodes[0].getStart() + 1)}plugins: [${plugin}],${viteConfigContents.slice(configNodes[0].getStart() + 1)}`;
}
else {
// Add nxViteTsPaths plugin
const pluginsArrayNodes = (0, tsquery_1.query)(pluginsNodes[0], 'ArrayLiteralExpression');
if (pluginsArrayNodes.length === 0) {
return;
}
newViteConfigContents = `${nxViteTsPathsImport}\n${viteConfigContents.slice(0, pluginsArrayNodes[0].getStart() + 1)}${plugin}${viteConfigContents.slice(pluginsArrayNodes[0].getStart() + 1)}`;
}
}
else {
const pluginOptionsNodes = (0, tsquery_1.query)(nxViteTsPathsNodes[0], 'ObjectLiteralExpression');
if (pluginOptionsNodes.length === 0) {
// Add the options
newViteConfigContents = `${viteConfigContents.slice(0, nxViteTsPathsNodes[0].getStart())}${plugin}${viteConfigContents.slice(nxViteTsPathsNodes[0].getEnd())}`;
}
else {
// update the object
newViteConfigContents = `${viteConfigContents.slice(0, pluginOptionsNodes[0].getStart() + 1)}buildLibsFromSource: options.buildLibsFromSource, ${viteConfigContents.slice(pluginOptionsNodes[0].getStart() + 1)}`;
}
}
tree.write(configPath, newViteConfigContents);
}

View File

@@ -0,0 +1,7 @@
import { type TargetConfiguration, type Tree } from '@nx/devkit';
import { AggregatedLog } from '@nx/devkit/src/generators/plugin-migrations/aggregate-log-util';
export declare function previewPostTargetTransformer(migrationLogs: AggregatedLog): (target: TargetConfiguration, tree: Tree, projectDetails: {
projectName: string;
root: string;
}, inferredTargetConfiguration: TargetConfiguration) => TargetConfiguration<any>;
//# sourceMappingURL=preview-post-target-transformer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"preview-post-target-transformer.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/convert-to-inferred/lib/preview-post-target-transformer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAEjE,OAAO,EAAE,aAAa,EAAE,MAAM,gEAAgE,CAAC;AAE/F,wBAAgB,4BAA4B,CAAC,aAAa,EAAE,aAAa,IAErE,QAAQ,mBAAmB,EAC3B,MAAM,IAAI,EACV,gBAAgB;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACrD,6BAA6B,mBAAmB,8BAuCnD"}

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.previewPostTargetTransformer = previewPostTargetTransformer;
const utils_1 = require("./utils");
function previewPostTargetTransformer(migrationLogs) {
return (target, tree, projectDetails, inferredTargetConfiguration) => {
const viteConfigPath = (0, utils_1.getViteConfigPath)(tree, projectDetails.root);
if (target.options) {
removePropertiesFromTargetOptions(target.options, projectDetails.projectName, migrationLogs);
}
if (target.configurations) {
for (const configurationName in target.configurations) {
const configuration = target.configurations[configurationName];
removePropertiesFromTargetOptions(configuration, projectDetails.projectName, migrationLogs);
}
if (Object.keys(target.configurations).length === 0) {
if ('defaultConfiguration' in target) {
delete target.defaultConfiguration;
}
delete target.configurations;
}
if ('defaultConfiguration' in target &&
!target.configurations[target.defaultConfiguration]) {
delete target.defaultConfiguration;
}
}
return target;
};
}
function removePropertiesFromTargetOptions(targetOptions, projectName, migrationLogs) {
if ('buildTarget' in targetOptions) {
delete targetOptions.buildTarget;
}
if ('staticFilePath' in targetOptions) {
delete targetOptions.staticFilePath;
}
if ('proxyConfig' in targetOptions) {
migrationLogs.addLog({
executorName: '@nx/vite:preview-server',
project: projectName,
log: `Encountered 'proxyConfig' in project.json. You will need to copy the contents of this file to the 'server.proxy' property in your Vite config file.`,
});
delete targetOptions.proxyConfig;
}
}

View File

@@ -0,0 +1,7 @@
import { type TargetConfiguration, type Tree } from '@nx/devkit';
import { AggregatedLog } from '@nx/devkit/src/generators/plugin-migrations/aggregate-log-util';
export declare function servePostTargetTransformer(migrationLogs: AggregatedLog): (target: TargetConfiguration, tree: Tree, projectDetails: {
projectName: string;
root: string;
}, inferredTargetConfiguration: TargetConfiguration) => TargetConfiguration<any>;
//# sourceMappingURL=serve-post-target-transformer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serve-post-target-transformer.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/convert-to-inferred/lib/serve-post-target-transformer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAEjE,OAAO,EAAE,aAAa,EAAE,MAAM,gEAAgE,CAAC;AAE/F,wBAAgB,0BAA0B,CAAC,aAAa,EAAE,aAAa,IAEnE,QAAQ,mBAAmB,EAC3B,MAAM,IAAI,EACV,gBAAgB;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACrD,6BAA6B,mBAAmB,8BA8CnD"}

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.servePostTargetTransformer = servePostTargetTransformer;
const utils_1 = require("./utils");
function servePostTargetTransformer(migrationLogs) {
return (target, tree, projectDetails, inferredTargetConfiguration) => {
const viteConfigPath = (0, utils_1.getViteConfigPath)(tree, projectDetails.root);
if (target.options) {
removePropertiesFromTargetOptions(tree, target.options, viteConfigPath, projectDetails.root, projectDetails.projectName, migrationLogs, true);
}
if (target.configurations) {
for (const configurationName in target.configurations) {
const configuration = target.configurations[configurationName];
removePropertiesFromTargetOptions(tree, configuration, viteConfigPath, projectDetails.root, projectDetails.projectName, migrationLogs);
}
if (Object.keys(target.configurations).length === 0) {
if ('defaultConfiguration' in target) {
delete target.defaultConfiguration;
}
delete target.configurations;
}
if ('defaultConfiguration' in target &&
!target.configurations[target.defaultConfiguration]) {
delete target.defaultConfiguration;
}
}
return target;
};
}
function removePropertiesFromTargetOptions(tree, targetOptions, viteConfigPath, projectRoot, projectName, migrationLogs, defaultOptions = false) {
if ('buildTarget' in targetOptions) {
delete targetOptions.buildTarget;
}
if ('buildLibsFromSource' in targetOptions) {
migrationLogs.addLog({
executorName: '@nx/vite:dev-server',
project: projectName,
log: `Encountered 'buildLibsFromSource' in project.json. This property will be added to your Vite config file via the '@nx/vite:build' executor migration.`,
});
delete targetOptions.buildLibsFromSource;
}
if ('hmr' in targetOptions) {
delete targetOptions.hmr;
}
if ('proxyConfig' in targetOptions) {
migrationLogs.addLog({
executorName: '@nx/vite:dev-server',
project: projectName,
log: `Encountered 'proxyConfig' in project.json. You will need to copy the contents of this file to the 'server.proxy' property in your Vite config file.`,
});
delete targetOptions.proxyConfig;
}
}

View File

@@ -0,0 +1,6 @@
import { type TargetConfiguration, type Tree } from '@nx/devkit';
export declare function testPostTargetTransformer(target: TargetConfiguration, tree: Tree, projectDetails: {
projectName: string;
root: string;
}, inferredTargetConfiguration: TargetConfiguration): TargetConfiguration<any>;
//# sourceMappingURL=test-post-target-transformer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"test-post-target-transformer.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/convert-to-inferred/lib/test-post-target-transformer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAIjE,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,mBAAmB,EAC3B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACrD,2BAA2B,EAAE,mBAAmB,4BA+CjD"}

View File

@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.testPostTargetTransformer = testPostTargetTransformer;
const utils_1 = require("./utils");
const plugin_migration_utils_1 = require("@nx/devkit/src/generators/plugin-migrations/plugin-migration-utils");
function testPostTargetTransformer(target, tree, projectDetails, inferredTargetConfiguration) {
if (target.options) {
removePropertiesFromTargetOptions(target.options, projectDetails.root);
}
if (target.configurations) {
for (const configurationName in target.configurations) {
const configuration = target.configurations[configurationName];
removePropertiesFromTargetOptions(configuration, projectDetails.root);
}
if (Object.keys(target.configurations).length === 0) {
if ('defaultConfiguration' in target) {
delete target.defaultConfiguration;
}
delete target.configurations;
}
if ('defaultConfiguration' in target &&
!target.configurations[target.defaultConfiguration]) {
delete target.defaultConfiguration;
}
}
if (target.outputs) {
(0, plugin_migration_utils_1.processTargetOutputs)(target, [{ newName: 'coverage.reportsDirectory', oldName: 'reportsDirectory' }], inferredTargetConfiguration, {
projectName: projectDetails.projectName,
projectRoot: projectDetails.root,
});
}
if (target.inputs &&
target.inputs.every((i) => i === 'default' || i === '^production')) {
delete target.inputs;
}
return target;
}
function removePropertiesFromTargetOptions(targetOptions, projectRoot) {
if ('configFile' in targetOptions) {
targetOptions.config = (0, utils_1.toProjectRelativePath)(targetOptions.configFile, projectRoot);
delete targetOptions.configFile;
}
if ('reportsDirectory' in targetOptions) {
if (targetOptions.reportsDirectory.startsWith('../')) {
targetOptions.reportsDirectory = targetOptions.reportsDirectory.replace(/(\.\.\/)+/, '');
}
targetOptions['coverage.reportsDirectory'] = (0, utils_1.toProjectRelativePath)(targetOptions.reportsDirectory, projectRoot);
delete targetOptions.reportsDirectory;
}
if ('testFiles' in targetOptions) {
targetOptions.testNamePattern = `"/(${targetOptions.testFiles
.map((f) => f.replace('.', '\\.'))
.join('|')})/"`;
delete targetOptions.testFiles;
}
}

View File

@@ -0,0 +1,5 @@
import { type Tree } from '@nx/devkit';
export declare function toProjectRelativePath(path: string, projectRoot: string): string;
export declare function getViteConfigPath(tree: Tree, root: string): string;
export declare function addConfigValuesToViteConfig(tree: Tree, configFile: string, configValues: Record<string, Record<string, unknown>>): void;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/convert-to-inferred/lib/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,IAAI,EAAqB,MAAM,YAAY,CAAC;AAGzE,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,GAClB,MAAM,CAaR;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,UASzD;AAED,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QA+BtD"}

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toProjectRelativePath = toProjectRelativePath;
exports.getViteConfigPath = getViteConfigPath;
exports.addConfigValuesToViteConfig = addConfigValuesToViteConfig;
const posix_1 = require("path/posix");
const devkit_1 = require("@nx/devkit");
const tsquery_1 = require("@phenomnomnominal/tsquery");
function toProjectRelativePath(path, projectRoot) {
if (projectRoot === '.') {
// workspace and project root are the same, we normalize it to ensure it
// works with Jest since some paths only work when they start with `./`
return path.startsWith('.') ? path : `./${path}`;
}
const relativePath = (0, posix_1.relative)((0, posix_1.resolve)(devkit_1.workspaceRoot, projectRoot), (0, posix_1.resolve)(devkit_1.workspaceRoot, path));
return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
}
function getViteConfigPath(tree, root) {
return [
(0, devkit_1.joinPathFragments)(root, `vite.config.ts`),
(0, devkit_1.joinPathFragments)(root, `vite.config.cts`),
(0, devkit_1.joinPathFragments)(root, `vite.config.mts`),
(0, devkit_1.joinPathFragments)(root, `vite.config.js`),
(0, devkit_1.joinPathFragments)(root, `vite.config.cjs`),
(0, devkit_1.joinPathFragments)(root, `vite.config.mjs`),
].find((f) => tree.exists(f));
}
function addConfigValuesToViteConfig(tree, configFile, configValues) {
const IMPORT_PROPERTY_SELECTOR = 'ImportDeclaration';
const viteConfigContents = tree.read(configFile, 'utf-8');
const sourceFile = (0, tsquery_1.ast)(viteConfigContents);
// AST TO GET SECTION TO APPEND TO
const importNodes = (0, tsquery_1.query)(sourceFile, IMPORT_PROPERTY_SELECTOR);
if (importNodes.length === 0) {
return;
}
const lastImportNode = importNodes[importNodes.length - 1];
const configValuesString = `
// These options were migrated by @nx/vite:convert-to-inferred from the project.json file.
const configValues = ${JSON.stringify(configValues)};
// Determine the correct configValue to use based on the configuration
const nxConfiguration = process.env.NX_TASK_TARGET_CONFIGURATION ?? 'default';
const options = {
...configValues.default,
...(configValues[nxConfiguration] ?? {})
}`;
tree.write(configFile, `${viteConfigContents.slice(0, lastImportNode.getEnd())}
${configValuesString}
${viteConfigContents.slice(lastImportNode.getEnd())}`);
}

View File

@@ -0,0 +1,19 @@
{
"$schema": "https://json-schema.org/schema",
"$id": "NxViteConvertToInferred",
"description": "Convert existing Vite project(s) using `@nx/vite:*` executors to use `@nx/vite/plugin`. Defaults to migrating all projects. Pass '--project' to migrate only one target.",
"title": "Convert Vite project from executor to plugin",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "The project to convert from using the `@nx/vite:*` executors to use `@nx/vite/plugin`.",
"x-priority": "important"
},
"skipFormat": {
"type": "boolean",
"description": "Whether to format files at the end of the migration.",
"default": false
}
}
}

7
node_modules/@nx/vite/src/generators/init/init.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { GeneratorCallback, Tree } from '@nx/devkit';
import { InitGeneratorSchema } from './schema';
export declare function updateNxJsonSettings(tree: Tree): void;
export declare function initGenerator(tree: Tree, schema: InitGeneratorSchema): Promise<GeneratorCallback>;
export declare function initGeneratorInternal(tree: Tree, schema: InitGeneratorSchema): Promise<GeneratorCallback>;
export default initGenerator;
//# sourceMappingURL=init.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../../../../packages/vite/src/generators/init/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,iBAAiB,EAGjB,IAAI,EAEL,MAAM,YAAY,CAAC;AAKpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAI/C,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,IAAI,QAe9C;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,mBAAmB,8BAEpE;AAED,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,mBAAmB,8BA2D5B;AAED,eAAe,aAAa,CAAC"}

69
node_modules/@nx/vite/src/generators/init/init.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateNxJsonSettings = updateNxJsonSettings;
exports.initGenerator = initGenerator;
exports.initGeneratorInternal = initGeneratorInternal;
const devkit_1 = require("@nx/devkit");
const add_plugin_1 = require("@nx/devkit/src/utils/add-plugin");
const setup_paths_plugin_1 = require("../setup-paths-plugin/setup-paths-plugin");
const plugin_1 = require("../../plugins/plugin");
const utils_1 = require("./lib/utils");
const ignore_vite_temp_files_1 = require("../../utils/ignore-vite-temp-files");
function updateNxJsonSettings(tree) {
const nxJson = (0, devkit_1.readNxJson)(tree);
const productionFileSet = nxJson.namedInputs?.production;
if (productionFileSet) {
productionFileSet.push('!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)', '!{projectRoot}/tsconfig.spec.json', '!{projectRoot}/src/test-setup.[jt]s');
nxJson.namedInputs.production = Array.from(new Set(productionFileSet));
}
(0, devkit_1.updateNxJson)(tree, nxJson);
}
function initGenerator(tree, schema) {
return initGeneratorInternal(tree, { addPlugin: false, ...schema });
}
async function initGeneratorInternal(tree, schema) {
const nxJson = (0, devkit_1.readNxJson)(tree);
const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
nxJson.useInferencePlugins !== false;
schema.addPlugin ??= addPluginDefault;
if (schema.addPlugin) {
await (0, add_plugin_1.addPlugin)(tree, await (0, devkit_1.createProjectGraphAsync)(), '@nx/vite/plugin', plugin_1.createNodesV2, {
buildTargetName: ['build', 'vite:build', 'vite-build'],
testTargetName: ['test', 'vite:test', 'vite-test'],
serveTargetName: ['serve', 'vite:serve', 'vite-serve'],
devTargetName: ['dev', 'vite:dev', 'vite-dev'],
previewTargetName: ['preview', 'vite:preview', 'vite-preview'],
serveStaticTargetName: [
'serve-static',
'vite:serve-static',
'vite-serve-static',
],
typecheckTargetName: ['typecheck', 'vite:typecheck', 'vite-typecheck'],
buildDepsTargetName: [
'build-deps',
'vite:build-deps',
'vite-build-deps',
],
watchDepsTargetName: [
'watch-deps',
'vite:watch-deps',
'vite-watch-deps',
],
}, schema.updatePackageScripts);
}
updateNxJsonSettings(tree);
await (0, ignore_vite_temp_files_1.ignoreViteTempFiles)(tree, schema.projectRoot);
if (schema.setupPathsPlugin) {
await (0, setup_paths_plugin_1.setupPathsPlugin)(tree, { skipFormat: true });
}
const tasks = [];
if (!schema.skipPackageJson) {
tasks.push((0, utils_1.moveToDevDependencies)(tree));
tasks.push(await (0, utils_1.checkDependenciesInstalled)(tree, schema));
}
if (!schema.skipFormat) {
await (0, devkit_1.formatFiles)(tree);
}
return (0, devkit_1.runTasksInSerial)(...tasks);
}
exports.default = initGenerator;

View File

@@ -0,0 +1,5 @@
import { Tree } from '@nx/devkit';
import { InitGeneratorSchema } from '../schema';
export declare function checkDependenciesInstalled(host: Tree, schema: InitGeneratorSchema): Promise<import("@nx/devkit").GeneratorCallback>;
export declare function moveToDevDependencies(tree: Tree): () => void;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../../../../packages/vite/src/generators/init/lib/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,IAAI,EAGL,MAAM,YAAY,CAAC;AAWpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAyBhD,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,mBAAmB,mDAuD5B;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,cAgB/C"}

79
node_modules/@nx/vite/src/generators/init/lib/utils.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkDependenciesInstalled = checkDependenciesInstalled;
exports.moveToDevDependencies = moveToDevDependencies;
const devkit_1 = require("@nx/devkit");
const versions_1 = require("@nx/js/src/utils/versions");
const semver_1 = require("semver");
const versions_2 = require("../../../utils/versions");
const version_utils_1 = require("../../../utils/version-utils");
function hasIncompatibleInstalledEsbuild(host) {
const installedEsbuildVersion = (0, devkit_1.getDependencyVersionFromPackageJson)(host, 'esbuild');
if (!installedEsbuildVersion) {
return false;
}
try {
return !(0, semver_1.intersects)(installedEsbuildVersion, versions_1.esbuildVersion, {
includePrerelease: true,
});
}
catch {
return true;
}
}
async function checkDependenciesInstalled(host, schema) {
const { vitest } = await (0, version_utils_1.getVitestDependenciesVersionsToInstall)(host);
// Determine which vite version to install:
// 1. Explicit flags take priority (useViteV5/V6/V7)
// 2. If vite is already installed, keep the matching major version
// 3. If esbuild is already installed but incompatible with Vite 8, use Vite 7
// 4. Otherwise, use the latest default (^8.0.0)
const installedMajor = (0, version_utils_1.getInstalledViteMajorVersion)(host);
const installedEsbuildVersion = (0, devkit_1.getDependencyVersionFromPackageJson)(host, 'esbuild');
const useViteV7ForEsbuildCompatibility = installedMajor == null && hasIncompatibleInstalledEsbuild(host);
if (useViteV7ForEsbuildCompatibility) {
devkit_1.output.warn({
title: 'Installed esbuild is incompatible with Vite 8. Using Vite 7.',
bodyLines: [
`Found esbuild version "${installedEsbuildVersion}" in the workspace root package.json.`,
`Update esbuild to a range compatible with ${versions_1.esbuildVersion} if you want newly generated Vite projects to use Vite 8 by default.`,
],
});
}
const viteVersionToInstall = schema.useViteV5
? versions_2.viteV5Version
: schema.useViteV6
? versions_2.viteV6Version
: schema.useViteV7 ||
installedMajor === 7 ||
useViteV7ForEsbuildCompatibility
? versions_2.viteV7Version
: installedMajor === 6
? versions_2.viteV6Version
: installedMajor === 5
? versions_2.viteV5Version
: versions_2.viteVersion;
return (0, devkit_1.addDependenciesToPackageJson)(host, {}, {
'@nx/vite': versions_2.nxVersion,
'@nx/web': versions_2.nxVersion,
vite: viteVersionToInstall,
vitest: vitest,
'@vitest/ui': vitest,
jiti: versions_2.jitiVersion,
}, undefined, schema.keepExistingVersions);
}
function moveToDevDependencies(tree) {
let wasUpdated = false;
(0, devkit_1.updateJson)(tree, 'package.json', (packageJson) => {
packageJson.dependencies = packageJson.dependencies || {};
packageJson.devDependencies = packageJson.devDependencies || {};
if (packageJson.dependencies['@nx/vite']) {
packageJson.devDependencies['@nx/vite'] =
packageJson.dependencies['@nx/vite'];
delete packageJson.dependencies['@nx/vite'];
wasUpdated = true;
}
return packageJson;
});
return wasUpdated ? () => (0, devkit_1.installPackagesTask)(tree) : () => { };
}

13
node_modules/@nx/vite/src/generators/init/schema.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
export interface InitGeneratorSchema {
skipFormat?: boolean;
setupPathsPlugin?: boolean;
skipPackageJson?: boolean;
keepExistingVersions?: boolean;
updatePackageScripts?: boolean;
addPlugin?: boolean;
vitestOnly?: boolean;
useViteV5?: boolean;
useViteV6?: boolean;
useViteV7?: boolean;
projectRoot?: string;
}

57
node_modules/@nx/vite/src/generators/init/schema.json generated vendored Normal file
View File

@@ -0,0 +1,57 @@
{
"cli": "nx",
"title": "Initialize Vite in the workspace.",
"description": "Initialize Vite in the workspace.",
"$id": "init-vite-plugin",
"type": "object",
"properties": {
"skipFormat": {
"description": "Skip formatting files.",
"type": "boolean",
"default": false
},
"skipPackageJson": {
"description": "Do not add dependencies to `package.json`.",
"type": "boolean",
"default": false
},
"setupPathsPlugin": {
"type": "boolean",
"description": "Updates vite config files to enable support for workspace libraries via the nxViteTsPaths plugin.",
"default": false
},
"keepExistingVersions": {
"type": "boolean",
"x-priority": "internal",
"description": "Keep existing dependencies versions",
"default": false
},
"updatePackageScripts": {
"type": "boolean",
"x-priority": "internal",
"description": "Update `package.json` scripts with inferred targets",
"default": false
},
"useViteV5": {
"type": "boolean",
"description": "Use Vite v5",
"default": false,
"x-priority": "internal",
"hidden": true
},
"useViteV6": {
"type": "boolean",
"description": "Use Vite v6",
"default": false,
"x-priority": "internal",
"hidden": true
},
"useViteV7": {
"type": "boolean",
"description": "Use Vite v7",
"default": false,
"x-priority": "internal",
"hidden": true
}
}
}

Some files were not shown because too many files have changed in this diff Show More