nx/packages/vite/plugins/nx-copy-assets.plugin.ts
Colum Ferry 985107cac3
fix(vite): ensure nxCopyAssetsPlugin outputs assets to correct location #28786 (#30585)
## Current Behavior
The `nxCopyAssetsPlugin` from `@nx/vite` does not output the asset files
to the correct location.
It prepends the `rootDir` even when the `outDir` in the `vite.config`
resolves to contain the `rootDir`.

## Expected Behavior
Only prepend the `rootDir` when it does not already exist

## Related Issue(s)

Fixes #28786
2025-04-02 13:30:55 +01:00

51 lines
1.6 KiB
TypeScript

import { join, relative } from 'node:path';
import type { Plugin, ResolvedConfig } from 'vite';
import { isDaemonEnabled, joinPathFragments, workspaceRoot } from '@nx/devkit';
import { AssetGlob } from '@nx/js/src/utils/assets/assets';
import { CopyAssetsHandler } from '@nx/js/src/utils/assets/copy-assets-handler';
export function nxCopyAssetsPlugin(_assets: (string | AssetGlob)[]): Plugin {
let config: ResolvedConfig;
let handler: CopyAssetsHandler;
let dispose: () => void;
if (global.NX_GRAPH_CREATION) return;
return {
name: 'nx-copy-assets-plugin',
configResolved(_config) {
config = _config;
},
async buildStart() {
const relativeProjectRoot = relative(workspaceRoot, config.root);
const assets = _assets.map((a) => {
if (typeof a === 'string') {
return joinPathFragments(relativeProjectRoot, a);
} else {
return {
...a,
input: joinPathFragments(relativeProjectRoot, a.input),
};
}
});
handler = new CopyAssetsHandler({
rootDir: workspaceRoot,
projectDir: config.root,
outputDir: config.build.outDir.startsWith(config.root)
? config.build.outDir
: join(config.root, config.build.outDir),
assets,
});
if (this.meta.watchMode && isDaemonEnabled()) {
dispose = await handler.watchAndProcessOnAssetChange();
}
},
async writeBundle() {
await handler.processAllAssetsOnce();
},
async closeWatcher() {
dispose == null ? void 0 : dispose();
},
};
}