From f04ed1f24af2ea4e78a46eba12ec5e89c15c4b94 Mon Sep 17 00:00:00 2001 From: Katerina Skroumpelou Date: Thu, 7 Dec 2023 15:45:08 +0200 Subject: [PATCH] fix(nuxt): correct outputs for nuxt and vite (#20627) --- packages/nuxt/package.json | 6 +- .../__snapshots__/application.spec.ts.snap | 1 + .../plugins/__snapshots__/plugin.spec.ts.snap | 14 +-- packages/nuxt/src/plugins/plugin.spec.ts | 20 ++-- packages/nuxt/src/plugins/plugin.ts | 103 ++++++++++++------ .../__snapshots__/library.spec.ts.snap | 6 + .../__snapshots__/configuration.spec.ts.snap | 27 +++++ .../vite/src/generators/init/init.spec.ts | 4 - packages/vite/src/generators/init/init.ts | 33 +++--- .../vitest/__snapshots__/vitest.spec.ts.snap | 3 + .../src/generators/vitest/vitest-generator.ts | 4 - .../update-vite-config.spec.ts.snap | 11 ++ .../update-17-2-0/lib/edit-build-config.ts | 64 ++++++++--- .../update-17-2-0/lib/edit-test-config.ts | 58 ++++++---- .../plugins/__snapshots__/plugin.spec.ts.snap | 12 +- packages/vite/src/plugins/plugin.ts | 57 +++++----- packages/vite/src/utils/generator-utils.ts | 18 +++ .../__snapshots__/application.spec.ts.snap | 5 + .../generators/application/lib/add-vite.ts | 6 +- .../__snapshots__/library.spec.ts.snap | 5 + .../plugins/__snapshots__/plugin.spec.ts.snap | 2 +- packages/webpack/src/plugins/plugin.ts | 2 +- 22 files changed, 310 insertions(+), 151 deletions(-) diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index 7ba40a15d5ff1..38c764b8092b2 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -36,8 +36,10 @@ "@nx/eslint": "file:../eslint", "@nx/vue": "file:../vue" }, + "peerDependencies": { + "vite": "^5.0.0" + }, "publishConfig": { "access": "public" - }, - "peerDependencies": {} + } } diff --git a/packages/nuxt/src/generators/application/__snapshots__/application.spec.ts.snap b/packages/nuxt/src/generators/application/__snapshots__/application.spec.ts.snap index 4ae08aedfc4bb..52e36ccc16ddd 100644 --- a/packages/nuxt/src/generators/application/__snapshots__/application.spec.ts.snap +++ b/packages/nuxt/src/generators/application/__snapshots__/application.spec.ts.snap @@ -121,6 +121,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../coverage/my-app', provider: 'v8', diff --git a/packages/nuxt/src/plugins/__snapshots__/plugin.spec.ts.snap b/packages/nuxt/src/plugins/__snapshots__/plugin.spec.ts.snap index 6a4bbc5d0fa46..696ca792bd0ef 100644 --- a/packages/nuxt/src/plugins/__snapshots__/plugin.spec.ts.snap +++ b/packages/nuxt/src/plugins/__snapshots__/plugin.spec.ts.snap @@ -13,7 +13,7 @@ exports[`@nx/nuxt/plugin not root project should create nodes 1`] = ` "^build-something", ], "inputs": [ - "default", + "production", "^production", { "externalDependencies": [ @@ -25,7 +25,7 @@ exports[`@nx/nuxt/plugin not root project should create nodes 1`] = ` "cwd": "my-app", }, "outputs": [ - "{options.outputPath}", + "{workspaceRoot}/dist/my-app/", ], }, "my-serve": { @@ -50,8 +50,7 @@ exports[`@nx/nuxt/plugin not root project should create nodes 1`] = ` "cwd": "my-app", }, "outputs": [ - "{options.reportsDirectory}", - "{workspaceRoot}/coverage/my-app", + "{workspaceRoot}/coverage/{projectRoot}", ], }, }, @@ -73,7 +72,7 @@ exports[`@nx/nuxt/plugin root project should create nodes 1`] = ` "^build", ], "inputs": [ - "default", + "production", "^production", { "externalDependencies": [ @@ -85,7 +84,7 @@ exports[`@nx/nuxt/plugin root project should create nodes 1`] = ` "cwd": ".", }, "outputs": [ - "{options.outputPath}", + "dist/my-app/", ], }, "serve": { @@ -110,8 +109,7 @@ exports[`@nx/nuxt/plugin root project should create nodes 1`] = ` "cwd": ".", }, "outputs": [ - "{options.reportsDirectory}", - "{projectRoot}/coverage", + "{workspaceRoot}/coverage/{projectRoot}", ], }, }, diff --git a/packages/nuxt/src/plugins/plugin.spec.ts b/packages/nuxt/src/plugins/plugin.spec.ts index a7774aff08044..f6190cddafb67 100644 --- a/packages/nuxt/src/plugins/plugin.spec.ts +++ b/packages/nuxt/src/plugins/plugin.spec.ts @@ -2,29 +2,35 @@ import { CreateNodesContext } from '@nx/devkit'; import { createNodes } from './plugin'; import { TempFs } from 'nx/src/internal-testing-utils/temp-fs'; -jest.mock('@nuxt/kit', () => ({ - loadNuxtConfig: jest.fn().mockImplementation(() => { +jest.mock('vite', () => ({ + loadConfigFromFile: jest.fn().mockImplementation(() => { return Promise.resolve({ - path: 'nuxt.config.ts', + path: 'vite.config.ts', config: {}, dependencies: [], }); }), })); +jest.mock('@nuxt/kit', () => ({ + loadNuxtConfig: jest.fn().mockImplementation(() => { + return Promise.resolve({ + buildDir: '../dist/my-app/.nuxt', + }); + }), +})); + jest.mock('../utils/executor-utils', () => ({ loadNuxtKitDynamicImport: jest.fn().mockResolvedValue({ loadNuxtConfig: jest.fn().mockResolvedValue({ - path: 'nuxt.config.ts', - config: {}, - dependencies: [], + buildDir: '../dist/my-app/.nuxt', }), }), })); - describe('@nx/nuxt/plugin', () => { let createNodesFunction = createNodes[1]; let context: CreateNodesContext; + describe('root project', () => { beforeEach(async () => { context = { diff --git a/packages/nuxt/src/plugins/plugin.ts b/packages/nuxt/src/plugins/plugin.ts index 29116dabb9949..bbc688f01b680 100644 --- a/packages/nuxt/src/plugins/plugin.ts +++ b/packages/nuxt/src/plugins/plugin.ts @@ -4,18 +4,19 @@ import { CreateNodesContext, detectPackageManager, joinPathFragments, - offsetFromRoot, readJsonFile, TargetConfiguration, + workspaceRoot, writeJsonFile, } from '@nx/devkit'; -import { basename, dirname, join } from 'path'; +import { basename, dirname, isAbsolute, join, relative } from 'path'; import { projectGraphCacheDirectory } from 'nx/src/utils/cache-directory'; import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs'; import { existsSync, readdirSync } from 'fs'; import { loadNuxtKitDynamicImport } from '../utils/executor-utils'; import { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes'; import { getLockFileName } from '@nx/js'; +import { loadConfigFromFile, UserConfig } from 'vite'; const cachePath = join(projectGraphCacheDirectory, 'nuxt.hash'); const targetsCache = existsSync(cachePath) ? readTargetsCache() : {}; @@ -90,11 +91,36 @@ async function buildNuxtTargets( options: NuxtPluginOptions, context: CreateNodesContext ) { + let viteConfig: + | { + path: string; + config: UserConfig; + dependencies: string[]; + } + | undefined; + if ( + existsSync( + joinPathFragments(context.workspaceRoot, projectRoot, 'vitest.config.ts') + ) + ) { + viteConfig = await loadConfigFromFile( + { + command: 'build', + mode: 'production', + }, + joinPathFragments(context.workspaceRoot, projectRoot, 'vitest.config.ts') + ); + } + const nuxtConfig: { buildDir: string; } = await getInfoFromNuxtConfig(configFilePath, context, projectRoot); - const { buildOutputs, testOutputs } = getOutputs(projectRoot, nuxtConfig); + const { buildOutputs, testOutputs } = getOutputs( + nuxtConfig, + viteConfig?.config, + projectRoot + ); const namedInputs = getNamedInputs(projectRoot, context); @@ -133,7 +159,7 @@ function buildTarget( dependsOn: [`^${buildTargetName}`], inputs: [ ...('production' in namedInputs - ? ['default', '^production'] + ? ['production', '^production'] : ['default', '^default']), { @@ -187,59 +213,64 @@ async function getInfoFromNuxtConfig( buildDir: string; }> { const { loadNuxtConfig } = await loadNuxtKitDynamicImport(); + const config = await loadNuxtConfig({ cwd: joinPathFragments(context.workspaceRoot, projectRoot), configFile: basename(configFilePath), }); return { - // to preserve only the relative path from the workspace root - // because nuxt automatically prepends the rootDir to buildDir - buildDir: config?.buildDir?.replace(config?.rootDir, ''), + buildDir: config?.buildDir, }; } function getOutputs( - projectRoot: string, - nuxtConfig: { - buildDir: string; - } + nuxtConfig: { buildDir: string }, + viteConfig: UserConfig, + projectRoot: string ): { buildOutputs: string[]; - outputPath: string; testOutputs: string[]; - reportsDirectory: string; } { - const buildOutputs = ['{options.outputPath}']; - const testOutputs = ['{options.reportsDirectory}']; + const reportsDirectory = + normalizeOutputPath( + viteConfig?.['test']?.coverage?.reportsDirectory, + projectRoot + ) ?? '{workspaceRoot}/coverage/{projectRoot}'; - function getOutput(path: string, projectRoot: string): string { - if (path.startsWith('..')) { - return join('{workspaceRoot}', join(projectRoot, path)); - } else { - return join('{projectRoot}', path); - } - } - - let distPath = undefined; + let nuxtBuildDir = nuxtConfig?.buildDir; if (nuxtConfig?.buildDir && basename(nuxtConfig?.buildDir) === '.nuxt') { // buildDir will most probably be `../dist/my-app/.nuxt` // we want the "general" outputPath to be `../dist/my-app` - distPath = nuxtConfig.buildDir.replace(basename(nuxtConfig.buildDir), ''); - buildOutputs.push(getOutput(distPath, projectRoot)); + nuxtBuildDir = nuxtConfig.buildDir.replace( + basename(nuxtConfig.buildDir), + '' + ); } + const buildOutputPath = + normalizeOutputPath(nuxtBuildDir, projectRoot) ?? + '{workspaceRoot}/dist/{projectRoot}'; - const outputPath = distPath ?? joinPathFragments('dist', projectRoot); - - const reportsDirectory = joinPathFragments( - offsetFromRoot(projectRoot), - 'coverage', - projectRoot - ); - - testOutputs.push(getOutput(reportsDirectory, projectRoot)); + return { + buildOutputs: [buildOutputPath], + testOutputs: [reportsDirectory], + }; +} - return { buildOutputs, outputPath, testOutputs, reportsDirectory }; +function normalizeOutputPath( + outputPath: string | undefined, + projectRoot: string +): string | undefined { + if (!outputPath) return undefined; + if (isAbsolute(outputPath)) { + return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`; + } else { + if (outputPath.startsWith('..')) { + return join('{workspaceRoot}', join(projectRoot, outputPath)); + } else { + return outputPath; + } + } } function normalizeOptions(options: NuxtPluginOptions): NuxtPluginOptions { diff --git a/packages/react/src/generators/library/__snapshots__/library.spec.ts.snap b/packages/react/src/generators/library/__snapshots__/library.spec.ts.snap index 4d4970fca14d7..324114ada1190 100644 --- a/packages/react/src/generators/library/__snapshots__/library.spec.ts.snap +++ b/packages/react/src/generators/library/__snapshots__/library.spec.ts.snap @@ -21,6 +21,7 @@ export default defineConfig({ cache: { dir: '../node_modules/.vitest' }, environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../coverage/my-lib', provider: 'v8' }, }, }); @@ -58,6 +59,10 @@ export default defineConfig({ // See: https://vitejs.dev/guide/build.html#library-mode build: { outDir: '../dist/my-lib', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, lib: { // Could also be a dictionary or array of multiple entry points. entry: 'src/index.ts', @@ -81,6 +86,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../coverage/my-lib', provider: 'v8', diff --git a/packages/vite/src/generators/configuration/__snapshots__/configuration.spec.ts.snap b/packages/vite/src/generators/configuration/__snapshots__/configuration.spec.ts.snap index b5ffd6de1c1b4..7d811246a8554 100644 --- a/packages/vite/src/generators/configuration/__snapshots__/configuration.spec.ts.snap +++ b/packages/vite/src/generators/configuration/__snapshots__/configuration.spec.ts.snap @@ -31,6 +31,10 @@ export default defineConfig({ // See: https://vitejs.dev/guide/build.html#library-mode build: { outDir: '../../dist/libs/react-lib-nonb-jest', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, lib: { // Could also be a dictionary or array of multiple entry points. entry: 'src/index.ts', @@ -80,6 +84,10 @@ export default defineConfig({ // See: https://vitejs.dev/guide/build.html#library-mode build: { outDir: '../../dist/libs/react-lib-nonb-jest', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, lib: { // Could also be a dictionary or array of multiple entry points. entry: 'src/index.ts', @@ -103,6 +111,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/libs/react-lib-nonb-jest', provider: 'v8', @@ -155,6 +164,10 @@ export default defineConfig({ cacheDir: '../../node_modules/.vite/libs/react-lib-nonb-vitest', build: { outDir: '../../dist/libs/react-lib-nonb-vitest', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, lib: { // Could also be a dictionary or array of multiple entry points. entry: 'src/index.ts', @@ -184,6 +197,7 @@ export default defineConfig({ cache: { dir: '../../node_modules/.vitest' }, environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/libs/react-lib-nonb-vitest', provider: 'v8', @@ -307,6 +321,10 @@ export default defineConfig({ build: { outDir: '../../dist/apps/my-test-react-app', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }, }); " @@ -450,6 +468,10 @@ export default defineConfig({ build: { outDir: '../../dist/apps/my-test-web-app', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }, }); " @@ -580,6 +602,10 @@ export default defineConfig({ build: { outDir: '../../dist/apps/my-test-react-app', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }, test: { @@ -590,6 +616,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/apps/my-test-react-app', provider: 'v8', diff --git a/packages/vite/src/generators/init/init.spec.ts b/packages/vite/src/generators/init/init.spec.ts index fae26ee007040..26fdc56821f33 100644 --- a/packages/vite/src/generators/init/init.spec.ts +++ b/packages/vite/src/generators/init/init.spec.ts @@ -93,10 +93,6 @@ describe('@nx/vite:init', () => { expect(vitestDefaults).toEqual({ cache: true, inputs: ['default', '^production'], - options: { - passWithNoTests: true, - reporters: ['default'], - }, }); }); }); diff --git a/packages/vite/src/generators/init/init.ts b/packages/vite/src/generators/init/init.ts index b8d57a9744408..a0c52c5b3c777 100644 --- a/packages/vite/src/generators/init/init.ts +++ b/packages/vite/src/generators/init/init.ts @@ -22,26 +22,21 @@ export function updateNxJsonSettings(tree: Tree) { nxJson.namedInputs.production = Array.from(new Set(productionFileSet)); } - nxJson.targetDefaults ??= {}; - nxJson.targetDefaults['@nx/vite:test'] ??= {}; - nxJson.targetDefaults['@nx/vite:test'].cache ??= true; - nxJson.targetDefaults['@nx/vite:test'].inputs ??= [ - 'default', - productionFileSet ? '^production' : '^default', - ]; - nxJson.targetDefaults['@nx/vite:test'].options ??= { - passWithNoTests: true, - reporters: ['default'], - }; - - nxJson.targetDefaults['@nx/vite:build'] ??= {}; + const hasPlugin = nxJson.plugins?.some((p) => + typeof p === 'string' + ? p === '@nx/vite/plugin' + : p.plugin === '@nx/vite/plugin' + ); - nxJson.targetDefaults['@nx/vite:build'].options ??= { - reportCompressedSize: true, - commonjsOptions: { - transformMixedEsModules: true, - }, - }; + if (!hasPlugin) { + nxJson.targetDefaults ??= {}; + nxJson.targetDefaults['@nx/vite:test'] ??= {}; + nxJson.targetDefaults['@nx/vite:test'].cache ??= true; + nxJson.targetDefaults['@nx/vite:test'].inputs ??= [ + 'default', + productionFileSet ? '^production' : '^default', + ]; + } updateNxJson(tree, nxJson); } diff --git a/packages/vite/src/generators/vitest/__snapshots__/vitest.spec.ts.snap b/packages/vite/src/generators/vitest/__snapshots__/vitest.spec.ts.snap index 38d86a317c4ab..30b843f7ffa4b 100644 --- a/packages/vite/src/generators/vitest/__snapshots__/vitest.spec.ts.snap +++ b/packages/vite/src/generators/vitest/__snapshots__/vitest.spec.ts.snap @@ -28,6 +28,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/apps/my-test-react-app', provider: 'v8', @@ -62,6 +63,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/apps/my-test-react-app', provider: 'v8', @@ -96,6 +98,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/libs/react-lib-nonb-jest', provider: 'v8', diff --git a/packages/vite/src/generators/vitest/vitest-generator.ts b/packages/vite/src/generators/vitest/vitest-generator.ts index 828efc9f88a7e..112c983849682 100644 --- a/packages/vite/src/generators/vitest/vitest-generator.ts +++ b/packages/vite/src/generators/vitest/vitest-generator.ts @@ -38,10 +38,6 @@ export async function vitestGenerator( tree, schema.project ); - let testTarget = - schema.testTarget ?? - findExistingTargetsInProject(targets).validFoundTargetName.test ?? - 'test'; const nxJson = readNxJson(tree); const hasPluginCheck = nxJson.plugins?.some( diff --git a/packages/vite/src/migrations/update-17-2-0/__snapshots__/update-vite-config.spec.ts.snap b/packages/vite/src/migrations/update-17-2-0/__snapshots__/update-vite-config.spec.ts.snap index a879a9cab4c23..ab4e52bdbc9db 100644 --- a/packages/vite/src/migrations/update-17-2-0/__snapshots__/update-vite-config.spec.ts.snap +++ b/packages/vite/src/migrations/update-17-2-0/__snapshots__/update-vite-config.spec.ts.snap @@ -10,6 +10,10 @@ export default defineConfig({ root: __dirname, build: { outDir: '../../dist/apps/demo', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }, cacheDir: '../../node_modules/.vite/demo', server: { @@ -39,6 +43,7 @@ export default defineConfig({ // }, test: { + reporters: ['default'], coverage: { reportsDirectory: '../../coverage/apps/demo', provider: 'v8', @@ -82,10 +87,13 @@ export default defineConfig({ build: { outDir: '../dist/demo2', + reportCompressedSize: true, + commonjsOptions: { transformMixedEsModules: true }, someProperty: 'someValue', }, test: { + reporters: ['default'], coverage: { reportsDirectory: '../coverage/demo2', provider: 'v8', @@ -136,10 +144,13 @@ export default defineConfig({ build: { outDir: '../dist/demo3', + reportCompressedSize: true, + commonjsOptions: { transformMixedEsModules: true }, someProperty: 'someValue', }, test: { + reporters: ['default'], coverage: { reportsDirectory: '../coverage/demo3', provider: 'v8', diff --git a/packages/vite/src/migrations/update-17-2-0/lib/edit-build-config.ts b/packages/vite/src/migrations/update-17-2-0/lib/edit-build-config.ts index 9deb336f80701..ddabd56521203 100644 --- a/packages/vite/src/migrations/update-17-2-0/lib/edit-build-config.ts +++ b/packages/vite/src/migrations/update-17-2-0/lib/edit-build-config.ts @@ -81,29 +81,63 @@ function fixBuild( configContents, `PropertyAssignment:has(Identifier[name="build"])` )?.[0]; - let buildOutDir: ts.Node[]; + if (buildObject) { - buildOutDir = tsquery.query( + const reportCompressedSizeExists = + tsquery.query( + buildObject, + `PropertyAssignment:has(Identifier[name="reportCompressedSize"])` + )?.length > 0; + + const commonjsOptionsExists = + tsquery.query( + buildObject, + `PropertyAssignment:has(Identifier[name="commonjsOptions"])` + )?.length > 0; + + const buildOutDir = tsquery.query( buildObject, `PropertyAssignment:has(Identifier[name="outDir"])` - ); - } + )?.length; - if (buildOutDir?.length > 0) { - return configContents; - } else if (buildObject) { - // has build, has no outDir - // so add outDir - return applyChangesToString(configContents, [ - { + // Array to store changes + let changes = []; + + // Add outDir if not present + if (!buildOutDir) { + changes.push({ type: ChangeType.Insert, index: buildObject.getStart() + `build: {`.length + 1, text: `outDir: '${outputPath}',`, - }, - ]); + }); + } + + // Add reportCompressedSize if not present + if (!reportCompressedSizeExists) { + changes.push({ + type: ChangeType.Insert, + index: buildObject.getStart() + `build: {`.length + 1, + text: `reportCompressedSize: true,`, + }); + } + + // Add commonjsOptions if not present + if (!commonjsOptionsExists) { + changes.push({ + type: ChangeType.Insert, + index: buildObject.getStart() + `build: {`.length + 1, + text: `commonjsOptions: { transformMixedEsModules: true },`, + }); + } + + if (changes.length > 0) { + return applyChangesToString(configContents, changes); + } } else { return addBuildProperty(configContents, outputPath, foundDefineConfig); } + + return configContents; } function addRoot( @@ -140,6 +174,10 @@ function addBuildProperty( index: foundDefineConfig.getStart() + 14, text: `build: { outDir: '${outputPath}', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, },`, }, ]); diff --git a/packages/vite/src/migrations/update-17-2-0/lib/edit-test-config.ts b/packages/vite/src/migrations/update-17-2-0/lib/edit-test-config.ts index 75e39660c2856..eec7fa8f3a5e8 100644 --- a/packages/vite/src/migrations/update-17-2-0/lib/edit-test-config.ts +++ b/packages/vite/src/migrations/update-17-2-0/lib/edit-test-config.ts @@ -19,11 +19,17 @@ export function updateTestConfig( let testCoverageDir: ts.Node; let testCoverage: ts.Node; let provider: ts.Node; + let reporters: ts.Node; + if (testObject) { testCoverage = tsquery.query( testObject, `PropertyAssignment:has(Identifier[name="coverage"])` )?.[0]; + reporters = tsquery.query( + testObject, + `PropertyAssignment:has(Identifier[name="reporters"])` + )?.[0]; if (testCoverage) { testCoverageDir = tsquery.query( testCoverage, @@ -48,41 +54,47 @@ export function updateTestConfig( ); } + let changes = []; + + if (!reporters && testObject) { + changes.push({ + type: ChangeType.Insert, + index: testObject.getStart() + `test: {`.length + 1, + text: `reporters: ['default'],`, + }); + } + if (testCoverageDir) { // Do nothing } else if (testCoverage) { // has test.coverage, has no reportsDirectory // so add reportsDirectory - configContents = applyChangesToString(configContents, [ - { + changes.push({ + type: ChangeType.Insert, + index: testCoverage.getStart() + `coverage: {`.length + 1, + text: `reportsDirectory: '${coverageDir}',`, + }); + if (!provider) { + changes.push({ type: ChangeType.Insert, index: testCoverage.getStart() + `coverage: {`.length + 1, - text: `reportsDirectory: '${coverageDir}',`, - }, - ]); - if (!provider) { - configContents = applyChangesToString(configContents, [ - { - type: ChangeType.Insert, - index: testCoverage.getStart() + `coverage: {`.length + 1, - text: `provider: 'v8',`, - }, - ]); + text: `provider: 'v8',`, + }); } } else if (testObject) { - configContents = applyChangesToString(configContents, [ - { - type: ChangeType.Insert, - index: testObject.getStart() + `test: {`.length + 1, - text: `coverage: { + changes.push({ + type: ChangeType.Insert, + index: testObject.getStart() + `test: {`.length + 1, + text: `coverage: { reportsDirectory: '${coverageDir}', provider: 'v8', },`, - }, - ]); - } else { - // has no test so do nothing + }); } - return configContents; + if (changes.length > 0) { + return applyChangesToString(configContents, changes); + } else { + return configContents; + } } diff --git a/packages/vite/src/plugins/__snapshots__/plugin.spec.ts.snap b/packages/vite/src/plugins/__snapshots__/plugin.spec.ts.snap index 279d6ebaf0986..693e374b8492c 100644 --- a/packages/vite/src/plugins/__snapshots__/plugin.spec.ts.snap +++ b/packages/vite/src/plugins/__snapshots__/plugin.spec.ts.snap @@ -25,7 +25,7 @@ exports[`@nx/vite/plugin not root project should create nodes 1`] = ` "cwd": "my-app", }, "outputs": [ - "{options.outputPath}", + "{workspaceRoot}/dist/{projectRoot}", ], }, "my-serve": { @@ -50,7 +50,7 @@ exports[`@nx/vite/plugin not root project should create nodes 1`] = ` "cache": true, "command": "vitest run", "inputs": [ - "production", + "default", "^production", { "externalDependencies": [ @@ -62,7 +62,7 @@ exports[`@nx/vite/plugin not root project should create nodes 1`] = ` "cwd": "my-app", }, "outputs": [ - "{options.reportsDirectory}", + "{workspaceRoot}/coverage/{projectRoot}", ], }, }, @@ -96,7 +96,7 @@ exports[`@nx/vite/plugin root project should create nodes 1`] = ` "cwd": ".", }, "outputs": [ - "{options.outputPath}", + "{workspaceRoot}/dist/{projectRoot}", ], }, "preview": { @@ -121,7 +121,7 @@ exports[`@nx/vite/plugin root project should create nodes 1`] = ` "cache": true, "command": "vitest run", "inputs": [ - "production", + "default", "^production", { "externalDependencies": [ @@ -133,7 +133,7 @@ exports[`@nx/vite/plugin root project should create nodes 1`] = ` "cwd": ".", }, "outputs": [ - "{options.reportsDirectory}", + "{workspaceRoot}/coverage/{projectRoot}", ], }, }, diff --git a/packages/vite/src/plugins/plugin.ts b/packages/vite/src/plugins/plugin.ts index 8b19af559dabd..c51d0163ec979 100644 --- a/packages/vite/src/plugins/plugin.ts +++ b/packages/vite/src/plugins/plugin.ts @@ -9,7 +9,7 @@ import { workspaceRoot, writeJsonFile, } from '@nx/devkit'; -import { dirname, isAbsolute, join, relative, resolve } from 'path'; +import { dirname, isAbsolute, join, relative } from 'path'; import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs'; import { loadConfigFromFile, UserConfig } from 'vite'; import { existsSync, readdirSync } from 'fs'; @@ -101,8 +101,8 @@ async function buildViteTargets( ); const { buildOutputs, testOutputs } = getOutputs( - projectRoot, - viteConfig?.config + viteConfig?.config, + projectRoot ); const namedInputs = getNamedInputs(projectRoot, context); @@ -191,7 +191,7 @@ async function testTarget( cache: true, inputs: [ ...('production' in namedInputs - ? ['production', '^production'] + ? ['default', '^production'] : ['default', '^default']), { externalDependencies: ['vitest'], @@ -213,35 +213,42 @@ function serveStaticTarget(options: VitePluginOptions) { } function getOutputs( - projectRoot: string, - viteConfig: UserConfig + viteConfig: UserConfig, + projectRoot: string ): { buildOutputs: string[]; testOutputs: string[]; } { const { build, test } = viteConfig; - const buildOutputs = ['{options.outputPath}']; - const testOutputs = ['{options.reportsDirectory}']; - - function getOutput(path: string, projectRoot: string): string { - if (path.startsWith('..')) { - return join('{workspaceRoot}', join(projectRoot, path)); - } else if (isAbsolute(resolve(path))) { - return `{workspaceRoot}/${relative(workspaceRoot, path)}`; - } else { - return join('{projectRoot}', path); - } - } - if (build?.outDir) { - buildOutputs.push(getOutput(build.outDir, projectRoot)); - } + const buildOutputPath = + normalizeOutputPath(build?.outDir, projectRoot) ?? + '{workspaceRoot}/dist/{projectRoot}'; - if (test?.coverage?.reportsDirectory) { - testOutputs.push(getOutput(test.coverage.reportsDirectory, projectRoot)); - } + const reportsDirectoryPath = + normalizeOutputPath(test?.coverage?.reportsDirectory, projectRoot) ?? + '{workspaceRoot}/coverage/{projectRoot}'; - return { buildOutputs, testOutputs }; + return { + buildOutputs: [buildOutputPath], + testOutputs: [reportsDirectoryPath], + }; +} + +function normalizeOutputPath( + outputPath: string | undefined, + projectRoot: string +): string | undefined { + if (!outputPath) return undefined; + if (isAbsolute(outputPath)) { + return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`; + } else { + if (outputPath.startsWith('..')) { + return join('{workspaceRoot}', join(projectRoot, outputPath)); + } else { + return outputPath; + } + } } function normalizeOptions(options: VitePluginOptions): VitePluginOptions { diff --git a/packages/vite/src/utils/generator-utils.ts b/packages/vite/src/utils/generator-utils.ts index 6c02a8c251c8a..c51fd8c6c3724 100644 --- a/packages/vite/src/utils/generator-utils.ts +++ b/packages/vite/src/utils/generator-utils.ts @@ -504,6 +504,10 @@ export function createOrEditViteConfig( // See: https://vitejs.dev/guide/build.html#library-mode build: { outDir: '${offsetFromRoot(projectRoot)}dist/${projectRoot}', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, lib: { // Could also be a dictionary or array of multiple entry points. entry: 'src/index.ts', @@ -521,6 +525,10 @@ export function createOrEditViteConfig( : ` build: { outDir: '${offsetFromRoot(projectRoot)}dist/${projectRoot}', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }, `; @@ -558,6 +566,7 @@ export function createOrEditViteConfig( ? `includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],` : '' } + reporters: ['default'], coverage: { reportsDirectory: '${offsetFromRoot(projectRoot)}coverage/${projectRoot}', provider: ${ @@ -812,9 +821,17 @@ function handleViteConfigFileExists( external: options.rollupOptionsExternal ?? [], }, outDir: `${offsetFromRoot}dist/${projectRoot}`, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, } : { outDir: `${offsetFromRoot}dist/${projectRoot}`, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }; const testOptionObject = { @@ -824,6 +841,7 @@ function handleViteConfigFileExists( }, environment: options.testEnvironment ?? 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: `${offsetFromRoot}coverage/${projectRoot}`, provider: `${options.coverageProvider ?? 'v8'}`, diff --git a/packages/vue/src/generators/application/__snapshots__/application.spec.ts.snap b/packages/vue/src/generators/application/__snapshots__/application.spec.ts.snap index 0b1a61b415bd1..7ae2708184915 100644 --- a/packages/vue/src/generators/application/__snapshots__/application.spec.ts.snap +++ b/packages/vue/src/generators/application/__snapshots__/application.spec.ts.snap @@ -68,6 +68,10 @@ export default defineConfig({ build: { outDir: '../dist/test', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, }, test: { @@ -78,6 +82,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../coverage/test', provider: 'v8', diff --git a/packages/vue/src/generators/application/lib/add-vite.ts b/packages/vue/src/generators/application/lib/add-vite.ts index d94274765db22..f3ac8c8ff6e26 100644 --- a/packages/vue/src/generators/application/lib/add-vite.ts +++ b/packages/vue/src/generators/application/lib/add-vite.ts @@ -39,8 +39,10 @@ export async function addVite( // Update build to skip type checking since tsc won't work on .vue files. // Need to use vue-tsc instead. const projectConfig = readProjectConfiguration(tree, options.name); - projectConfig.targets.build.options.skipTypeCheck = true; - updateProjectConfiguration(tree, options.name, projectConfig); + if (projectConfig.targets?.build?.options) { + projectConfig.targets.build.options.skipTypeCheck = true; + updateProjectConfiguration(tree, options.name, projectConfig); + } return viteTask; } diff --git a/packages/vue/src/generators/library/__snapshots__/library.spec.ts.snap b/packages/vue/src/generators/library/__snapshots__/library.spec.ts.snap index dc9843b800d76..5901ed52b3d27 100644 --- a/packages/vue/src/generators/library/__snapshots__/library.spec.ts.snap +++ b/packages/vue/src/generators/library/__snapshots__/library.spec.ts.snap @@ -58,6 +58,10 @@ export default defineConfig({ // See: https://vitejs.dev/guide/build.html#library-mode build: { outDir: '../dist/my-lib', + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, lib: { // Could also be a dictionary or array of multiple entry points. entry: 'src/index.ts', @@ -81,6 +85,7 @@ export default defineConfig({ environment: 'jsdom', include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + reporters: ['default'], coverage: { reportsDirectory: '../coverage/my-lib', provider: 'v8', diff --git a/packages/webpack/src/plugins/__snapshots__/plugin.spec.ts.snap b/packages/webpack/src/plugins/__snapshots__/plugin.spec.ts.snap index 5034861acf477..46bbd1d43f7e2 100644 --- a/packages/webpack/src/plugins/__snapshots__/plugin.spec.ts.snap +++ b/packages/webpack/src/plugins/__snapshots__/plugin.spec.ts.snap @@ -13,7 +13,7 @@ exports[`@nx/webpack/plugin should create nodes 1`] = ` "^build-something", ], "inputs": [ - "default", + "production", "^production", { "externalDependencies": [ diff --git a/packages/webpack/src/plugins/plugin.ts b/packages/webpack/src/plugins/plugin.ts index 0752df23d4f54..fdfefde3bd772 100644 --- a/packages/webpack/src/plugins/plugin.ts +++ b/packages/webpack/src/plugins/plugin.ts @@ -130,7 +130,7 @@ async function createWebpackTargets( inputs: 'production' in namedInputs ? [ - 'default', + 'production', '^production', { externalDependencies: ['webpack-cli'],