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

chore: check and build if outputDir does not exist before preview #11579

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 18 additions & 1 deletion packages/vite/src/node/preview.ts
@@ -1,6 +1,9 @@
import path from 'node:path'
import fs from 'node:fs'
import type * as http from 'node:http'
import sirv from 'sirv'
import colors from 'picocolors'
import spawn from 'cross-spawn'
import connect from 'connect'
import type { Connect } from 'dep-types/connect'
import corsMiddleware from 'cors'
Expand Down Expand Up @@ -83,6 +86,21 @@ export async function preview(
'production',
)

const distDir = path.resolve(config.root, config.build.outDir)
const isAlreadyBuild = fs.existsSync(distDir)
if (!isAlreadyBuild) {
const { status, error } = spawn.sync('npx', ['vite', 'build'])
Copy link
Member

Choose a reason for hiding this comment

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

I don't think we should execute vite build within preview. It feels a bit too automatic, and doesn't work for metaframeworks that use preview API but has a different build command too.

I think for now it's better to leave it as-is. If we really want to check, we could see if any plugins implement configurePreviewServer before issuing the warning. We might also want to do that if it's running through the vite preview command, as using the preview API, the consumer could adjust previewServer.httpServer themselves.

if (status !== 0 || error) {
config.logger.info(
colors.red(
colors.bold(
' > The outputDir cannot be found, the preview server cannot return the corresponding file',
),
),
)
}
}

const app = connect() as Connect.Server
const httpServer = await resolveHttpServer(
config.preview,
Expand Down Expand Up @@ -115,7 +133,6 @@ export async function preview(
config.base === './' || config.base === '' ? '/' : config.base

// static assets
const distDir = path.resolve(config.root, config.build.outDir)
const headers = config.preview.headers
const assetServer = sirv(distDir, {
etag: true,
Expand Down