import { getNamedInputs, getReadyCheckReadyWhen, PluginCache, hashFile, hashObject, workspaceDataDirectory, } from '@nx/devkit/internal'; import { sendsReadySignal } from '../utils/dev-server-ready-signal'; import { CreateNodesContext, createNodesFromFiles, CreateNodes, detectPackageManager, PackageManager, ProjectConfiguration, readJsonFile, workspaceRoot, hashArray, getPackageManagerCommand, TargetConfiguration, normalizePath, joinPathFragments, } from '@nx/devkit'; import { getLockFileName, getRootTsConfigPath } from '@nx/js'; import { BUN_INSTALL_SETTINGS_INPUTS, isUsingTsSolutionSetup, pnpmInstallSettingsInputsForInferredTarget, shouldIncludeBunInstallSettingsInputs, shouldIncludePnpmMajorRuntimeInput, addBuildAndWatchDepsTargets, } from '@nx/js/internal'; import { readdirSync } from 'fs'; import { basename, dirname, extname, isAbsolute, join, relative, resolve, } from 'path'; import { readRspackOptions } from '../utils/read-rspack-options'; import { resolveUserDefinedRspackConfig } from '../utils/resolve-user-defined-rspack-config'; export interface RspackPluginOptions { buildTargetName?: string; serveTargetName?: string; serveStaticTargetName?: string; previewTargetName?: string; buildDepsTargetName?: string; watchDepsTargetName?: string; } type RspackTargets = Pick; const rspackConfigGlob = '**/rspack.config.{js,ts,mjs,mts,cjs,cts}'; export const createNodes: CreateNodes = [ rspackConfigGlob, async (configFilePaths, options, context) => { const optionsHash = hashObject(options); const cachePath = join( workspaceDataDirectory, `rspack-${optionsHash}.hash` ); const targetsCache = new PluginCache(cachePath); const isTsSolutionSetup = isUsingTsSolutionSetup(); const packageManager = detectPackageManager(context.workspaceRoot); const pmc = getPackageManagerCommand(packageManager); const lockFileName = getLockFileName(packageManager); const includePnpmMajorRuntimeInput = shouldIncludePnpmMajorRuntimeInput( packageManager, context.workspaceRoot ); const includeBunInstallSettingsInputs = shouldIncludeBunInstallSettingsInputs( packageManager, context.workspaceRoot ); try { return await createNodesFromFiles( (configFile, options, context) => createNodesInternal( configFile, options, context, targetsCache, isTsSolutionSetup, packageManager, pmc, lockFileName, includePnpmMajorRuntimeInput, includeBunInstallSettingsInputs ), configFilePaths, options, context ); } finally { targetsCache.writeToDisk(); } }, ]; /** * @deprecated Use {@link createNodes} instead. This will be removed in Nx 24. */ export const createNodesV2 = createNodes; async function createNodesInternal( configFilePath: string, options: RspackPluginOptions, context: CreateNodesContext, targetsCache: PluginCache, isTsSolutionSetup: boolean, packageManager: PackageManager, pmc: ReturnType, lockFileName: string, includePnpmMajorRuntimeInput: boolean, includeBunInstallSettingsInputs: boolean ) { const projectRoot = dirname(configFilePath); // Do not create a project if package.json and project.json isn't there. const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot)); if ( !siblingFiles.includes('package.json') && !siblingFiles.includes('project.json') ) { return {}; } let packageJson = {}; if (siblingFiles.includes('package.json')) { packageJson = readJsonFile( join(context.workspaceRoot, projectRoot, 'package.json') ); } const normalizedOptions = normalizeOptions(options); const lockFileHash = hashFile(join(context.workspaceRoot, lockFileName)) ?? ''; const nodeHash = hashArray([ hashFile(join(context.workspaceRoot, configFilePath)), lockFileHash, hashObject({ ...options, isTsSolutionSetup, includePnpmMajorRuntimeInput, includeBunInstallSettingsInputs, }), hashObject(packageJson), ]); // We do not want to alter how the hash is calculated, so appending the config file path to the hash // to prevent vite/vitest files overwriting the target cache created by the other const hash = `${nodeHash}_${configFilePath}`; if (!targetsCache.has(hash)) { targetsCache.set( hash, await createRspackTargets( configFilePath, projectRoot, normalizedOptions, context, isTsSolutionSetup, packageManager, pmc, includePnpmMajorRuntimeInput, includeBunInstallSettingsInputs ) ); } const { targets, metadata } = targetsCache.get(hash); return { projects: { [projectRoot]: { root: projectRoot, targets, metadata, }, }, }; } async function createRspackTargets( configFilePath: string, projectRoot: string, options: RspackPluginOptions, context: CreateNodesContext, isTsSolutionSetup: boolean, packageManager: PackageManager, pmc: ReturnType, includePnpmMajorRuntimeInput: boolean, includeBunInstallSettingsInputs: boolean ): Promise { const namedInputs = getNamedInputs(projectRoot, context); const rspackConfig = await resolveUserDefinedRspackConfig( join(context.workspaceRoot, configFilePath), getRootTsConfigPath(), true ); const rspackOptions = await readRspackOptions(rspackConfig); const outputs = []; for (const config of rspackOptions) { if (config.output?.path) { outputs.push(normalizeOutputPath(config.output.path, projectRoot)); } } const targets = {}; const env: NodeJS.ProcessEnv = {}; const isTsConfig = ['.ts', '.cts', '.mts'].includes(extname(configFilePath)); if (isTsConfig) { // https://rspack.dev/config/#using-ts-node env['TS_NODE_COMPILER_OPTIONS'] = JSON.stringify({ module: 'CommonJS', moduleResolution: 'Node10', customConditions: null, }); } const buildInputs: TargetConfiguration['inputs'] = [ ...('production' in namedInputs ? ['production', '^production'] : ['default', '^default']), { externalDependencies: ['@rspack/cli'], }, ]; targets[options.buildTargetName] = { command: `rspack build`, options: { cwd: projectRoot, args: ['--node-env=production'], env, }, configurations: { development: { args: ['--node-env=development'], }, }, cache: true, dependsOn: [`^${options.buildTargetName}`], inputs: [ ...buildInputs, // A dependency consumed as built is read from its build's outputs. { dependentTasksOutputFiles: '**/*', transitive: true }, // The build can emit a pruned pnpm or Bun deploy output // (NxAppRspackPlugin with generatePackageJson), whose install settings // come from these otherwise-unhashed root sources. ...(packageManager === 'pnpm' ? pnpmInstallSettingsInputsForInferredTarget( includePnpmMajorRuntimeInput ) : []), ...(includeBunInstallSettingsInputs ? BUN_INSTALL_SETTINGS_INPUTS : []), ], outputs, metadata: { technologies: ['rspack'], description: 'Runs Rspack build', help: { command: `${pmc.exec} rspack build --help`, example: { options: { json: 'stats.json', }, }, }, }, }; const devServerReadyWhen = getDevServerReadyWhen( configFilePath, rspackOptions ); targets[options.serveTargetName] = { continuous: true, inputs: [...buildInputs], command: `rspack serve`, options: { cwd: projectRoot, args: ['--node-env=development'], env, }, readyWhen: devServerReadyWhen, metadata: { technologies: ['rspack'], description: 'Starts Rspack dev server', help: { command: `${pmc.exec} rspack serve --help`, example: { options: { port: 4201, }, }, }, }, }; targets[options.previewTargetName] = { continuous: true, inputs: [...buildInputs], command: `rspack serve`, options: { cwd: projectRoot, args: ['--node-env=production'], env, }, readyWhen: devServerReadyWhen, metadata: { technologies: ['rspack'], description: 'Starts Rspack dev server in production mode', help: { command: `${pmc.exec} rspack serve --help`, example: { options: { port: 4201, }, }, }, }, }; targets[options.serveStaticTargetName] = { dependsOn: [`${options.buildTargetName}`], continuous: true, inputs: [...buildInputs], executor: '@nx/web:file-server', options: { buildTarget: options.buildTargetName, spa: true, }, readyWhen: { signal: true }, }; // for `convert-to-inferred` we need to leave the port undefined or the options will not match if (rspackConfig.devServer?.port && rspackConfig.devServer?.port !== 4200) { targets[options.serveStaticTargetName].options.port = rspackConfig.devServer.port; } 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', ]; } addBuildAndWatchDepsTargets( context.workspaceRoot, projectRoot, targets, options, pmc ); return { targets, metadata: {} }; } function normalizeOptions(options: RspackPluginOptions): RspackPluginOptions { options ??= {}; options.buildTargetName ??= 'build'; options.serveTargetName ??= 'serve'; options.previewTargetName ??= 'preview'; options.serveStaticTargetName ??= 'serve-static'; return options; } function normalizeOutputPath( outputPath: string | undefined, projectRoot: string ): string | undefined { if (!outputPath) { // If outputPath is undefined, use rspack's default `dist` directory. if (projectRoot === '.') { return `{projectRoot}/dist`; } else { return `{workspaceRoot}/dist/{projectRoot}`; } } else { if (isAbsolute(outputPath)) { /** * If outputPath is absolute, we need to resolve it relative to the workspaceRoot first. * After that, we can use the relative path to the workspaceRoot token {workspaceRoot} to generate the output path. */ return `{workspaceRoot}/${normalizePath( relative(workspaceRoot, resolve(workspaceRoot, outputPath)) )}`; } else { if (outputPath.startsWith('..')) { return joinPathFragments('{workspaceRoot}', projectRoot, outputPath); } else { return joinPathFragments('{projectRoot}', outputPath); } } } } // A dev server whose config loads NxAppRspackPlugin, NxReadySignalPlugin or // @nx/angular-rspack's NgRspackPlugin reports when it listens. Otherwise the // check reads the config when the task runs, with the task's env and options, // and waits for the dev server's port. function getDevServerReadyWhen( configFilePath: string, configs: { devServer?: unknown; plugins?: unknown[] }[] ): TargetConfiguration['readyWhen'] { // `rspack serve` starts one dev server, for the first config with devServer const signals = sendsReadySignal( configs.find((config) => config.devServer) ?? configs[0] ?? {} ); return signals ? { signal: true } : getReadyCheckReadyWhen( '@nx/rspack/ready-check', basename(configFilePath) ); }