Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(vite): vitest migration add reporters #20823

Merged
merged 1 commit into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/vite/migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@
"description": "Update vite config.",
"implementation": "./src/migrations/update-17-2-0/update-vite-config"
},
"vitest-coverage-threshold": {
"vitest-coverage-and-reporters": {
"version": "17.3.0-beta.0",
"description": "Move the vitest coverage thresholds in their own object if exists.",
"implementation": "./src/migrations/update-17-3-0/vitest-coverage-threshold"
"description": "Move the vitest coverage thresholds in their own object if exists and add reporters.",
"implementation": "./src/migrations/update-17-3-0/vitest-coverage-and-reporters"
}
},
"packageJsonUpdates": {
Expand Down
7 changes: 5 additions & 2 deletions packages/vite/src/executors/dev-server/dev-server.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ export async function* viteDevServerExecutor(
projectRoot,
buildTargetOptions.configFile
);
const { serverOptions, otherOptions } = await getServerExtraArgs(options);
const { serverOptions, otherOptions } = await getServerExtraArgs({
...options,
...buildTargetOptions,
Comment on lines +41 to +42
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So buildTarget options should override the serve target options? 🤔

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, because ideally there would not be any overriding done, since there are no common options in serve and build. In any case, it's better to configure your project in vite.config.ts!

if this surfaces any errors we can revisit, but we're trying to keep the executor logic as minimal as possible.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see how this may seem confusing or wrong, however here's the thing:

When the options are loaded in the executor, the executor loads the main options from build, along with the options under the development configuration, for example:

    "build": {
      "executor": "@nx/vite:build",
      "outputs": ["{options.outputPath}"],
      "defaultConfiguration": "production",
      "options": {
        "outputPath": "dist/apps/my-app",
        "generatePackageJson": false
      },
      "configurations": {
        "development": {
          "mode": "development",
          "watch": true
        },
        "production": {
          "mode": "production"
        }
      }
    },
    "serve": {
      "executor": "@nx/vite:dev-server",
      "options": {
        "buildTarget": "my-app:build"
      },
      "configurations": {
        "development": {
          "buildTarget": "my-app:build:development",
          "hmr": true
        },
        "production": {
          "buildTarget": "my-app:build:production",
          "hmr": false
        }
      }
    },

It's up to the user to make sure these are set the way the user prefers.

In this case, it would load from build the following:

{
        "outputPath": "dist/apps/my-app",
        "generatePackageJson": false,
        "mode": "development",
         "watch": true
 }

And the options that would be loaded from serve would be:

{
          "buildTarget": "my-app:build:development",
          "hmr": true
 }

All these will be simplified in the near future, when we will be moving away from executors, and the logic will be much more transparent.

Copy link
Contributor

@viniciusbsneto viniciusbsneto Dec 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh! I see! serve and build targets have different schemas.

So that's why ideally there shouldn't be any overrides. It's the extra args that kinda allows the overriding. That got me confused. Although it's possible to setup mode in the serve target options, it shouldn't be done. Is that correct?

Thanks for the taking the time to explain! 🙇🏻‍♂️

});
const resolved = await loadConfigFromFile(
{
mode: otherOptions?.mode ?? 'development',
mode: otherOptions?.mode ?? buildTargetOptions?.['mode'] ?? 'development',
command: 'serve',
},
viteConfigPath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export async function* vitePreviewServerExecutor(
const { previewOptions, otherOptions } = await getExtraArgs(options);
const resolved = await loadConfigFromFile(
{
mode: otherOptions?.mode ?? 'production',
mode: otherOptions?.mode ?? otherOptionsFromBuild?.mode ?? 'production',
command: 'build',
},
viteConfigPath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import viteTsConfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
cacheDir: '../../node_modules/.vite/demo6',
test: {
reporters: ['default'],
globals: true,
cache: {
dir: '../node_modules/.vitest',
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: {
thresholds: {
branches: 75,
Expand All @@ -37,13 +37,13 @@ import viteTsConfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
cacheDir: '../../node_modules/.vite/demo3',
test: {
reporters: ['default'],
globals: true,
cache: {
dir: '../node_modules/.vitest',
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: {
thresholds: {
lines: 100,
Expand Down Expand Up @@ -97,13 +97,13 @@ import viteTsConfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
cacheDir: '../../node_modules/.vite/demo5',
test: {
reporters: ['default'],
globals: true,
cache: {
dir: '../node_modules/.vitest',
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: {
thresholds: {
lines: 100,
Expand All @@ -128,13 +128,13 @@ import viteTsConfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
cacheDir: '../../node_modules/.vite/demo2',
test: {
reporters: ['default'],
globals: true,
cache: {
dir: '../node_modules/.vitest',
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: {
reportsDirectory: '../coverage/demo2',
provider: 'v8',
Expand All @@ -153,6 +153,7 @@ import viteTsConfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
cacheDir: '../../node_modules/.vite/demo',
test: {
reporters: ['default'],
globals: true,
cache: {
dir: '../../node_modules/.vitest',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { ChangeType, applyChangesToString } from '@nx/devkit';
import { tsquery } from '@phenomnomnominal/tsquery';
import ts = require('typescript');

export function fixCoverageAndRerporters(
configContents: string
): string | undefined {
const configNode = getConfigNode(configContents);
if (!configNode) {
return;
}

const testHasCoverage = tsquery.query(
configNode,
`PropertyAssignment:has(Identifier[name="test"]):has(PropertyAssignment:has(Identifier[name="coverage"]))`
)?.[0];
let changes = [];

if (testHasCoverage) {
const testObjectLiteralExpressionNode = tsquery.query(
testHasCoverage,
`ObjectLiteralExpression:has(Identifier[name="coverage"])`
)?.[0];
const coverageNode = findCoverageNode(testObjectLiteralExpressionNode);

if (!coverageNode) {
return;
}

const linesNode = tsquery.query(
coverageNode,
`PropertyAssignment:has(Identifier[name="lines"])`
)?.[0];

const statementsNode = tsquery.query(
coverageNode,
`PropertyAssignment:has(Identifier[name="statements"])`
)?.[0];

const functionsNode = tsquery.query(
coverageNode,
`PropertyAssignment:has(Identifier[name="functions"])`
)?.[0];

const branchesNode = tsquery.query(
coverageNode,
`PropertyAssignment:has(Identifier[name="branches"])`
)?.[0];

if (linesNode) {
changes.push({
type: ChangeType.Delete,
start: linesNode.getStart(),
length: linesNode.getWidth() + 1,
});
}
if (statementsNode) {
changes.push({
type: ChangeType.Delete,
start: statementsNode.getStart(),
length: statementsNode.getWidth() + 1,
});
}

if (functionsNode) {
changes.push({
type: ChangeType.Delete,
start: functionsNode.getStart(),
length: functionsNode.getWidth() + 1,
});
}

if (branchesNode) {
changes.push({
type: ChangeType.Delete,
start: branchesNode.getStart(),
length: branchesNode.getWidth() + 1,
});
}

if (branchesNode || functionsNode || statementsNode || linesNode) {
changes.push({
type: ChangeType.Insert,
index: coverageNode.getStart() + 1,
text: `thresholds: {
${linesNode ? linesNode.getText() + ',' : ''}
${statementsNode ? statementsNode.getText() + ',' : ''}
${functionsNode ? functionsNode.getText() + ',' : ''}
${branchesNode ? branchesNode.getText() + ',' : ''}
},`,
});
}
}

const testHasReporters = tsquery.query(
configNode,
`PropertyAssignment:has(Identifier[name="test"]):has(PropertyAssignment:has(Identifier[name="reporters"]))`
)?.[0];

if (!testHasReporters) {
const testObject = tsquery.query(
configNode,
`PropertyAssignment:has(Identifier[name="test"])`
)?.[0];
changes.push({
type: ChangeType.Insert,
index: testObject.getStart() + `test: {`.length + 1,
text: `reporters: ['default'],`,
});
}

if (changes.length > 0) {
return applyChangesToString(configContents, changes);
} else {
return;
}
}

export function getConfigNode(configFileContents: string): ts.Node | undefined {
if (!configFileContents) {
return;
}
let configNode = tsquery.query(
configFileContents,
`ObjectLiteralExpression`
)?.[0];

const arrowFunctionReturnStatement = tsquery.query(
configFileContents,
`ArrowFunction Block ReturnStatement ObjectLiteralExpression`
)?.[0];

if (arrowFunctionReturnStatement) {
configNode = arrowFunctionReturnStatement;
}

return configNode;
}

function findCoverageNode(testNode: ts.Node) {
let coverageNode: ts.Node | undefined;
testNode.forEachChild((child) => {
if (ts.isPropertyAssignment(child) && child.name.getText() === 'coverage') {
coverageNode = child.initializer;
}
});
return coverageNode;
}
132 changes: 0 additions & 132 deletions packages/vite/src/migrations/update-17-3-0/lib/fix-coverage.ts

This file was deleted.

Loading