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): plugin should infer serve target if server config defined #27370 #27507

Merged
merged 1 commit into from
Aug 19, 2024
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
148 changes: 147 additions & 1 deletion packages/vite/src/plugins/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('@nx/vite/plugin', () => {

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

it('should create nodes', async () => {
Expand Down Expand Up @@ -113,6 +114,7 @@ describe('@nx/vite/plugin', () => {

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

it('should create nodes', async () => {
Expand Down Expand Up @@ -171,8 +173,152 @@ describe('@nx/vite/plugin', () => {
);

expect(nodes).toMatchSnapshot();
tempFs.cleanup();
});
it('should not exclude serve and preview targets when vite.config.ts is in library mode when user has defined a server config', async () => {
const tempFs = new TempFs('test-exclude');
(loadViteDynamicImport as jest.Mock).mockResolvedValue({
resolveConfig: jest.fn().mockResolvedValue({
build: {
lib: {
entry: 'index.ts',
name: 'my-lib',
},
},
server: {},
}),
}),
(context = {
configFiles: [],
nxJsonConfiguration: {
namedInputs: {
default: ['{projectRoot}/**/*'],
production: ['!{projectRoot}/**/*.spec.ts'],
},
},
workspaceRoot: tempFs.tempDir,
});
tempFs.createFileSync(
'my-lib/project.json',
JSON.stringify({ name: 'my-lib' })
);
tempFs.createFileSync('my-lib/vite.config.ts', '');

jest.resetModules();
const nodes = await createNodesFunction(
['my-lib/vite.config.ts'],
{
buildTargetName: 'build',
serveTargetName: 'serve',
previewTargetName: 'preview',
},
context
);

expect(nodes).toMatchInlineSnapshot(`
[
[
"my-lib/vite.config.ts",
{
"projects": {
"my-lib": {
"metadata": {},
"projectType": "library",
"root": "my-lib",
"targets": {
"build": {
"cache": true,
"command": "vite build",
"dependsOn": [
"^build",
],
"inputs": [
"production",
"^production",
{
"externalDependencies": [
"vite",
],
},
],
"metadata": {
"description": "Run Vite build",
"help": {
"command": "npx vite build --help",
"example": {
"options": {
"manifest": "manifest.json",
"sourcemap": true,
},
},
},
"technologies": [
"vite",
],
},
"options": {
"cwd": "my-lib",
},
"outputs": [
"{workspaceRoot}/dist/{projectRoot}",
],
},
"preview": {
"command": "vite preview",
"dependsOn": [
"build",
],
"metadata": {
"description": "Locally preview Vite production build",
"help": {
"command": "npx vite preview --help",
"example": {
"options": {
"port": 3000,
},
},
},
"technologies": [
"vite",
],
},
"options": {
"cwd": "my-lib",
},
},
"serve": {
"command": "vite serve",
"metadata": {
"description": "Starts Vite dev server",
"help": {
"command": "npx vite --help",
"example": {
"options": {
"port": 3000,
},
},
},
"technologies": [
"vite",
],
},
"options": {
"cwd": "my-lib",
},
},
"serve-static": {
"executor": "@nx/web:file-server",
"options": {
"buildTarget": "build",
"spa": true,
},
},
},
},
},
},
],
]
`);
});
});
});
33 changes: 17 additions & 16 deletions packages/vite/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,13 @@ async function createNodesInternal(
[getLockFileName(detectPackageManager(context.workspaceRoot))]
)) + configFilePath;

targetsCache[hash] ??= await buildViteTargets(
const { isLibrary, ...viteTargets } = await buildViteTargets(
configFilePath,
projectRoot,
normalizedOptions,
context
);
targetsCache[hash] ??= viteTargets;

const { targets, metadata } = targetsCache[hash];
const project: ProjectConfiguration = {
Expand All @@ -126,9 +127,7 @@ async function createNodesInternal(
// If project is buildable, then the project type.
// If it is not buildable, then leave it to other plugins/project.json to set the project type.
if (project.targets[options.buildTargetName]) {
project.projectType = project.targets[options.serveTargetName]
? 'application'
: 'library';
project.projectType = isLibrary ? 'library' : 'application';
}

return {
Expand All @@ -143,7 +142,7 @@ async function buildViteTargets(
projectRoot: string,
options: VitePluginOptions,
context: CreateNodesContext
): Promise<ViteTargets> {
): Promise<ViteTargets & { isLibrary: boolean }> {
const absoluteConfigFilePath = joinPathFragments(
context.workspaceRoot,
configFilePath
Expand All @@ -157,27 +156,25 @@ async function buildViteTargets(
// do nothing
}
const { resolveConfig } = await loadViteDynamicImport();
const viteConfig = await resolveConfig(
const viteBuildConfig = await resolveConfig(
{
configFile: absoluteConfigFilePath,
mode: 'development',
},
'build'
);

const { buildOutputs, testOutputs, hasTest, isBuildable } = getOutputs(
viteConfig,
projectRoot,
context.workspaceRoot
);
const { buildOutputs, testOutputs, hasTest, isBuildable, hasServeConfig } =
getOutputs(viteBuildConfig, projectRoot, context.workspaceRoot);

const namedInputs = getNamedInputs(projectRoot, context);

const targets: Record<string, TargetConfiguration> = {};

// If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static
const hasRemixPlugin =
viteConfig.plugins && viteConfig.plugins.some((p) => p.name === 'remix');
viteBuildConfig.plugins &&
viteBuildConfig.plugins.some((p) => p.name === 'remix');
if (
!configFilePath.includes('vitest.config') &&
!hasRemixPlugin &&
Expand All @@ -191,7 +188,7 @@ async function buildViteTargets(
);

// If running in library mode, then there is nothing to serve.
if (!viteConfig.build?.lib) {
if (!viteBuildConfig.build?.lib || hasServeConfig) {
targets[options.serveTargetName] = serveTarget(projectRoot);
targets[options.previewTargetName] = previewTarget(
projectRoot,
Expand All @@ -211,7 +208,7 @@ async function buildViteTargets(
}

const metadata = {};
return { targets, metadata };
return { targets, metadata, isLibrary: Boolean(viteBuildConfig.build?.lib) };
}

async function buildTarget(
Expand Down Expand Up @@ -349,16 +346,17 @@ function serveStaticTarget(options: VitePluginOptions) {
}

function getOutputs(
viteConfig: Record<string, any> | undefined,
viteBuildConfig: Record<string, any> | undefined,
projectRoot: string,
workspaceRoot: string
): {
buildOutputs: string[];
testOutputs: string[];
hasTest: boolean;
isBuildable: boolean;
hasServeConfig: boolean;
} {
const { build, test } = viteConfig;
const { build, test, server } = viteBuildConfig;

const buildOutputPath = normalizeOutputPath(
build?.outDir,
Expand All @@ -372,6 +370,8 @@ function getOutputs(
build?.rollupOptions?.input ||
existsSync(join(workspaceRoot, projectRoot, 'index.html'));

const hasServeConfig = Boolean(server);

const reportsDirectoryPath = normalizeOutputPath(
test?.coverage?.reportsDirectory,
projectRoot,
Expand All @@ -384,6 +384,7 @@ function getOutputs(
testOutputs: [reportsDirectoryPath],
hasTest: !!test,
isBuildable,
hasServeConfig,
};
}

Expand Down