Skip to content

Commit

Permalink
fix(misc): use the ts sync generator with other bundler tasks (#29170)
Browse files Browse the repository at this point in the history
<!-- Please make sure you have read the submission guidelines before
posting an PR -->
<!--
https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr
-->

<!-- Please make sure that your commit message follows our format -->
<!-- Example: `fix(nx): must begin with lowercase` -->

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

## Current Behavior
<!-- This is the behavior we have today -->

Only targets using `tsc` trigger the `@nx/js:typescript-sync` generator
to run.

## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->

Generating projects with other bundlers should also infer the
`@nx/js:typescript-sync` generator in their relevant targets.

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #
  • Loading branch information
leosvelperez authored Dec 5, 2024
1 parent 7c25cf1 commit e9a07da
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 27 deletions.
2 changes: 1 addition & 1 deletion packages/js/src/generators/setup-build/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { addBuildTargetDefaults } from '@nx/devkit/src/generators/target-default
import { basename, dirname, join } from 'node:path/posix';
import { mergeTargetConfigurations } from 'nx/src/devkit-internals';
import type { PackageJson } from 'nx/src/utils/package-json';
import { ensureProjectIsIncludedInPluginRegistrations } from '../..//utils/typescript/plugin';
import { ensureProjectIsIncludedInPluginRegistrations } from '../../utils/typescript/plugin';
import { getImportPath } from '../../utils/get-import-path';
import {
getUpdatedPackageJsonContent,
Expand Down
24 changes: 19 additions & 5 deletions packages/rollup/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { getLockFileName } from '@nx/js';
import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';
import { type RollupOptions } from 'rollup';
import { hashObject } from 'nx/src/hasher/file-hasher';
import { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';

const pmc = getPackageManagerCommand();

Expand Down Expand Up @@ -59,7 +60,8 @@ export const createNodes: CreateNodes<RollupPluginOptions> = [
configFilePath,
normalizeOptions(options),
context,
{}
{},
isUsingTsSolutionSetup()
);
},
];
Expand All @@ -74,6 +76,7 @@ export const createNodesV2: CreateNodesV2<RollupPluginOptions> = [
`rollup-${optionsHash}.hash`
);
const targetsCache = readTargetsCache(cachePath);
const isTsSolutionSetup = isUsingTsSolutionSetup();

try {
return await createNodesFromFiles(
Expand All @@ -82,7 +85,8 @@ export const createNodesV2: CreateNodesV2<RollupPluginOptions> = [
configFile,
normalizedOptions,
context,
targetsCache
targetsCache,
isTsSolutionSetup
),
configFilePaths,
normalizedOptions,
Expand All @@ -98,7 +102,8 @@ async function createNodesInternal(
configFilePath: string,
options: Required<RollupPluginOptions>,
context: CreateNodesContext,
targetsCache: Record<string, Record<string, TargetConfiguration>>
targetsCache: Record<string, Record<string, TargetConfiguration>>,
isTsSolutionSetup: boolean
) {
const projectRoot = dirname(configFilePath);
const fullyQualifiedProjectRoot = join(context.workspaceRoot, projectRoot);
Expand All @@ -123,7 +128,8 @@ async function createNodesInternal(
configFilePath,
projectRoot,
options,
context
context,
isTsSolutionSetup
);

return {
Expand All @@ -140,7 +146,8 @@ async function buildRollupTarget(
configFilePath: string,
projectRoot: string,
options: RollupPluginOptions,
context: CreateNodesContext
context: CreateNodesContext,
isTsSolutionSetup: boolean
): Promise<Record<string, TargetConfiguration>> {
let loadConfigFile: (
path: string,
Expand Down Expand Up @@ -200,6 +207,13 @@ async function buildRollupTarget(
},
},
};

if (isTsSolutionSetup) {
targets[options.buildTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
}

return targets;
}

Expand Down
34 changes: 30 additions & 4 deletions packages/rspack/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';
import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';
import { getLockFileName, getRootTsConfigPath } from '@nx/js';
import { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';
import { existsSync, readdirSync } from 'fs';
import { hashObject } from 'nx/src/hasher/file-hasher';
import { workspaceDataDirectory } from 'nx/src/utils/cache-directory';
Expand Down Expand Up @@ -54,10 +55,17 @@ export const createNodesV2: CreateNodesV2<RspackPluginOptions> = [
`rspack-${optionsHash}.hash`
);
const targetsCache = readTargetsCache(cachePath);
const isTsSolutionSetup = isUsingTsSolutionSetup();
try {
return await createNodesFromFiles(
(configFile, options, context) =>
createNodesInternal(configFile, options, context, targetsCache),
createNodesInternal(
configFile,
options,
context,
targetsCache,
isTsSolutionSetup
),
configFilePaths,
options,
context
Expand All @@ -72,7 +80,8 @@ async function createNodesInternal(
configFilePath: string,
options: RspackPluginOptions,
context: CreateNodesContext,
targetsCache: Record<string, RspackTargets>
targetsCache: Record<string, RspackTargets>,
isTsSolutionSetup: boolean
) {
const projectRoot = dirname(configFilePath);
// Do not create a project if package.json and project.json isn't there.
Expand Down Expand Up @@ -100,7 +109,8 @@ async function createNodesInternal(
configFilePath,
projectRoot,
normalizedOptions,
context
context,
isTsSolutionSetup
);

const { targets, metadata } = targetsCache[hash];
Expand All @@ -120,7 +130,8 @@ async function createRspackTargets(
configFilePath: string,
projectRoot: string,
options: RspackPluginOptions,
context: CreateNodesContext
context: CreateNodesContext,
isTsSolutionSetup: boolean
): Promise<RspackTargets> {
const namedInputs = getNamedInputs(projectRoot, context);

Expand Down Expand Up @@ -187,6 +198,21 @@ async function createRspackTargets(
},
};

if (isTsSolutionSetup) {
targets[options.buildTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
targets[options.serveTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
targets[options.previewTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
targets[options.serveStaticTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
}

return { targets, metadata: {} };
}

Expand Down
35 changes: 31 additions & 4 deletions packages/vite/src/plugins/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ jest.mock('../utils/executor-utils', () => ({

jest.mock('@nx/js/src/utils/typescript/ts-solution-setup', () => ({
...jest.requireActual('@nx/js/src/utils/typescript/ts-solution-setup'),
isUsingTsSolutionSetup: jest.fn().mockReturnValue(false),
isUsingTsSolutionSetup: jest.fn(),
}));

describe('@nx/vite/plugin', () => {
let createNodesFunction = createNodesV2[1];
let context: CreateNodesContext;

beforeEach(() => {
(isUsingTsSolutionSetup as jest.Mock).mockReturnValue(false);
});

describe('root project', () => {
let tempFs: TempFs;
beforeEach(async () => {
Expand All @@ -42,12 +46,11 @@ describe('@nx/vite/plugin', () => {
};
tempFs.createFileSync('vite.config.ts', '');
tempFs.createFileSync('index.html', '');
tempFs.createFileSync('package.json', '');
tempFs.createFileSync('package.json', '{}');
});

afterEach(() => {
jest.resetModules();
tempFs.cleanup();
});

it('should create nodes', async () => {
Expand Down Expand Up @@ -95,7 +98,7 @@ describe('@nx/vite/plugin', () => {
});

it('should infer typecheck with --build flag when using TS solution setup', async () => {
(isUsingTsSolutionSetup as jest.Mock).mockResolvedValue(true);
(isUsingTsSolutionSetup as jest.Mock).mockReturnValue(true);
tempFs.createFileSync('tsconfig.json', '');

const nodes = await createNodesFunction(
Expand All @@ -114,6 +117,30 @@ describe('@nx/vite/plugin', () => {
`tsc --build --emitDeclarationOnly --pretty --verbose`
);
});

it('should infer the sync generator when using TS solution setup', async () => {
(isUsingTsSolutionSetup as jest.Mock).mockReturnValue(true);
tempFs.createFileSync('tsconfig.json', '');

const nodes = await createNodesFunction(
['vite.config.ts'],
{
buildTargetName: 'build',
serveTargetName: 'serve',
previewTargetName: 'preview',
testTargetName: 'test',
serveStaticTargetName: 'serve-static',
},
context
);

expect(nodes[0][1].projects['.'].targets.build.syncGenerators).toEqual([
'@nx/js:typescript-sync',
]);
expect(
nodes[0][1].projects['.'].targets.typecheck.syncGenerators
).toEqual(['@nx/js:typescript-sync']);
});
});

describe('not root project', () => {
Expand Down
49 changes: 41 additions & 8 deletions packages/vite/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export interface VitePluginOptions {
type ViteTargets = Pick<ProjectConfiguration, 'targets' | 'metadata'>;

function readTargetsCache(cachePath: string): Record<string, ViteTargets> {
return existsSync(cachePath) ? readJsonFile(cachePath) : {};
return process.env.NX_CACHE_PROJECT_GRAPH !== 'false' && existsSync(cachePath)
? readJsonFile(cachePath)
: {};
}

function writeTargetsToCache(cachePath, results?: Record<string, ViteTargets>) {
Expand Down Expand Up @@ -208,17 +210,24 @@ async function buildViteTargets(
options.buildTargetName,
namedInputs,
buildOutputs,
projectRoot
projectRoot,
isUsingTsSolutionSetup
);

// If running in library mode, then there is nothing to serve.
if (!viteBuildConfig.build?.lib || hasServeConfig) {
targets[options.serveTargetName] = serveTarget(projectRoot);
targets[options.serveTargetName] = serveTarget(
projectRoot,
isUsingTsSolutionSetup
);
targets[options.previewTargetName] = previewTarget(
projectRoot,
options.buildTargetName
);
targets[options.serveStaticTargetName] = serveStaticTarget(options) as {};
targets[options.serveStaticTargetName] = serveStaticTarget(
options,
isUsingTsSolutionSetup
);
}
}

Expand Down Expand Up @@ -251,6 +260,12 @@ async function buildViteTargets(
},
},
};

if (isUsingTsSolutionSetup) {
targets[options.typecheckTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
}
}

// if file is vitest.config or vite.config has definition for test, create target for test
Expand All @@ -272,9 +287,10 @@ async function buildTarget(
[inputName: string]: any[];
},
outputs: string[],
projectRoot: string
projectRoot: string,
isUsingTsSolutionSetup: boolean
) {
return {
const buildTarget: TargetConfiguration = {
command: `vite build`,
options: { cwd: joinPathFragments(projectRoot) },
cache: true,
Expand Down Expand Up @@ -302,9 +318,15 @@ async function buildTarget(
},
},
};

if (isUsingTsSolutionSetup) {
buildTarget.syncGenerators = ['@nx/js:typescript-sync'];
}

return buildTarget;
}

function serveTarget(projectRoot: string) {
function serveTarget(projectRoot: string, isUsingTsSolutionSetup: boolean) {
const targetConfig: TargetConfiguration = {
command: `vite serve`,
options: {
Expand All @@ -324,6 +346,10 @@ function serveTarget(projectRoot: string) {
},
};

if (isUsingTsSolutionSetup) {
targetConfig.syncGenerators = ['@nx/js:typescript-sync'];
}

return targetConfig;
}

Expand Down Expand Up @@ -388,7 +414,10 @@ async function testTarget(
};
}

function serveStaticTarget(options: VitePluginOptions) {
function serveStaticTarget(
options: VitePluginOptions,
isUsingTsSolutionSetup: boolean
) {
const targetConfig: TargetConfiguration = {
executor: '@nx/web:file-server',
options: {
Expand All @@ -397,6 +426,10 @@ function serveStaticTarget(options: VitePluginOptions) {
},
};

if (isUsingTsSolutionSetup) {
targetConfig.syncGenerators = ['@nx/js:typescript-sync'];
}

return targetConfig;
}

Expand Down
Loading

0 comments on commit e9a07da

Please sign in to comment.