Upgrade to Vite 4 (#5685)

* Upgrade Vite 4

* Simplify Svelte preprocess setup

* Upgrade rollup

* Fix tests

* Fix wrong changeset target

* Fix error tests

* Set NODE_ENV default
This commit is contained in:
Bjorn Lu 2023-01-04 02:24:49 +08:00 committed by GitHub
parent 5007bc7881
commit f6cf92b483
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 388 additions and 3510 deletions

View file

@ -0,0 +1,7 @@
---
'astro': major
'@astrojs/svelte': major
'@astrojs/vue': major
---
Upgrade to Vite 4. Please see its [migration guide](https://vitejs.dev/guide/migration.html) for more information.

View file

@ -0,0 +1,5 @@
---
'@astrojs/svelte': major
---
Simplify Svelte preprocess setup. `<style lang="postcss">` is now required if using PostCSS inside style tags.

View file

@ -1,26 +0,0 @@
import { expect } from '@playwright/test';
import { testFactory, getErrorOverlayContent } from './test-utils.js';
const test = testFactory({
experimental: { errorOverlay: true },
root: './fixtures/error-react-spectrum/',
});
let devServer;
test.beforeAll(async ({ astro }) => {
devServer = await astro.startDevServer();
});
test.afterAll(async ({ astro }) => {
await devServer.stop();
});
test.describe('Error: React Spectrum', () => {
test('overlay', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/'));
const message = (await getErrorOverlayContent(page)).hint;
expect(message).toMatch('@adobe/react-spectrum is not compatible');
});
});

View file

@ -1,7 +0,0 @@
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
// https://astro.build/config
export default defineConfig({
integrations: [react()],
});

View file

@ -1,12 +0,0 @@
{
"name": "@e2e/error-react-spectrum",
"version": "0.0.0",
"private": true,
"dependencies": {
"@adobe/react-spectrum": "^3.18.0",
"@astrojs/react": "workspace:*",
"astro": "workspace:*",
"react": "^18.1.0",
"react-dom": "^18.1.0"
}
}

View file

@ -1,19 +0,0 @@
---
// Just importing causes a failure
import '@adobe/react-spectrum';
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<style>
</style>
</head>
<body>
<main>
testing
</main>
</body>
</html>

View file

@ -156,7 +156,6 @@
"recast": "^0.20.5", "recast": "^0.20.5",
"rehype": "^12.0.1", "rehype": "^12.0.1",
"resolve": "^1.22.0", "resolve": "^1.22.0",
"rollup": "^2.79.1",
"semver": "^7.3.7", "semver": "^7.3.7",
"shiki": "^0.11.1", "shiki": "^0.11.1",
"sirv": "^2.0.2", "sirv": "^2.0.2",
@ -168,8 +167,8 @@
"typescript": "*", "typescript": "*",
"unist-util-visit": "^4.1.0", "unist-util-visit": "^4.1.0",
"vfile": "^5.3.2", "vfile": "^5.3.2",
"vite": "~3.2.5", "vite": "^4.0.3",
"vitefu": "^0.2.1", "vitefu": "^0.2.4",
"yargs-parser": "^21.0.1", "yargs-parser": "^21.0.1",
"zod": "^3.17.3" "zod": "^3.17.3"
}, },
@ -207,6 +206,7 @@
"rehype-slug": "^5.0.1", "rehype-slug": "^5.0.1",
"rehype-toc": "^3.0.2", "rehype-toc": "^3.0.2",
"remark-code-titles": "^0.1.2", "remark-code-titles": "^0.1.2",
"rollup": "^3.9.0",
"sass": "^1.52.2", "sass": "^1.52.2",
"srcset-parse": "^1.1.0", "srcset-parse": "^1.1.0",
"unified": "^10.1.2" "unified": "^10.1.2"

View file

@ -156,6 +156,11 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
} }
} }
// Start with a default NODE_ENV so Vite doesn't set an incorrect default when loading the Astro config
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = cmd === 'dev' ? 'development' : 'production';
}
let { astroConfig: initialAstroConfig, userConfig: initialUserConfig } = await openConfig({ let { astroConfig: initialAstroConfig, userConfig: initialUserConfig } = await openConfig({
cwd: root, cwd: root,
flags, flags,

View file

@ -25,7 +25,6 @@ import markdownVitePlugin from '../vite-plugin-markdown/index.js';
import astroScannerPlugin from '../vite-plugin-scanner/index.js'; import astroScannerPlugin from '../vite-plugin-scanner/index.js';
import astroScriptsPlugin from '../vite-plugin-scripts/index.js'; import astroScriptsPlugin from '../vite-plugin-scripts/index.js';
import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js'; import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js';
import { createCustomViteLogger } from './errors/dev/index.js';
import { resolveDependency } from './util.js'; import { resolveDependency } from './util.js';
interface CreateViteOptions { interface CreateViteOptions {
@ -197,7 +196,7 @@ export async function createVite(
sortPlugins(result.plugins); sortPlugins(result.plugins);
} }
result.customLogger = createCustomViteLogger(result.logLevel ?? 'warn'); result.customLogger = vite.createLogger(result.logLevel ?? 'warn');
return result; return result;
} }

View file

@ -1,2 +1,2 @@
export { collectErrorMetadata } from './utils.js'; export { collectErrorMetadata } from './utils.js';
export { createCustomViteLogger, enhanceViteSSRError, getViteErrorPayload } from './vite.js'; export { enhanceViteSSRError, getViteErrorPayload } from './vite.js';

View file

@ -12,11 +12,6 @@ import { normalizeLF } from '../utils.js';
type EsbuildMessage = ESBuildTransformResult['warnings'][number]; type EsbuildMessage = ESBuildTransformResult['warnings'][number];
export const incompatiblePackages = {
'react-spectrum': `@adobe/react-spectrum is not compatible with Vite's server-side rendering mode at the moment. You can still use React Spectrum from the client. Create an island React component and use the client:only directive. From there you can use React Spectrum.`,
};
export const incompatPackageExp = new RegExp(`(${Object.keys(incompatiblePackages).join('|')})`);
/** /**
* Takes any error-like object and returns a standardized Error + metadata object. * Takes any error-like object and returns a standardized Error + metadata object.
* Useful for consistent reporting regardless of where the error surfaced from. * Useful for consistent reporting regardless of where the error surfaced from.
@ -135,12 +130,6 @@ ${
See https://docs.astro.build/en/guides/troubleshooting/#document-or-window-is-not-defined for more information. See https://docs.astro.build/en/guides/troubleshooting/#document-or-window-is-not-defined for more information.
`; `;
return hint; return hint;
} else {
const res = incompatPackageExp.exec(err.stack);
if (res) {
const key = res[0] as keyof typeof incompatiblePackages;
return incompatiblePackages[key];
}
} }
return err.hint; return err.hint;
} }

View file

@ -1,28 +1,12 @@
import * as fs from 'fs'; import * as fs from 'fs';
import { getHighlighter } from 'shiki'; import { getHighlighter } from 'shiki';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import { createLogger, type ErrorPayload, type Logger, type LogLevel } from 'vite'; import type { ErrorPayload } from 'vite';
import type { ModuleLoader } from '../../module-loader/index.js'; import type { ModuleLoader } from '../../module-loader/index.js';
import { AstroErrorData } from '../errors-data.js'; import { AstroErrorData } from '../errors-data.js';
import { type ErrorWithMetadata } from '../errors.js'; import type { ErrorWithMetadata } from '../errors.js';
import { createSafeError } from '../utils.js'; import { createSafeError } from '../utils.js';
import { incompatPackageExp, renderErrorMarkdown } from './utils.js'; import { renderErrorMarkdown } from './utils.js';
/**
* Custom logger with better error reporting for incompatible packages
*/
export function createCustomViteLogger(logLevel: LogLevel): Logger {
const viteLogger = createLogger(logLevel);
const logger: Logger = {
...viteLogger,
error(msg, options?) {
// Silence warnings from incompatible packages (we log better errors for these)
if (incompatPackageExp.test(msg)) return;
return viteLogger.error(msg, options);
},
};
return logger;
}
export function enhanceViteSSRError(error: unknown, filePath?: URL, loader?: ModuleLoader): Error { export function enhanceViteSSRError(error: unknown, filePath?: URL, loader?: ModuleLoader): Error {
// NOTE: We don't know where the error that's coming here comes from, so we need to be defensive regarding what we do // NOTE: We don't know where the error that's coming here comes from, so we need to be defensive regarding what we do
@ -44,25 +28,23 @@ export function enhanceViteSSRError(error: unknown, filePath?: URL, loader?: Mod
// Vite has a fairly generic error message when it fails to load a module, let's try to enhance it a bit // Vite has a fairly generic error message when it fails to load a module, let's try to enhance it a bit
// https://github.com/vitejs/vite/blob/ee7c28a46a6563d54b828af42570c55f16b15d2c/packages/vite/src/node/ssr/ssrModuleLoader.ts#L91 // https://github.com/vitejs/vite/blob/ee7c28a46a6563d54b828af42570c55f16b15d2c/packages/vite/src/node/ssr/ssrModuleLoader.ts#L91
if (/failed to load module for ssr:/.test(safeError.message)) { let importName: string | undefined;
const importName = safeError.message.split('for ssr:').at(1)?.trim(); if ((importName = safeError.message.match(/Failed to load url (.*?) \(resolved id:/)?.[1])) {
if (importName) { safeError.title = AstroErrorData.FailedToLoadModuleSSR.title;
safeError.title = AstroErrorData.FailedToLoadModuleSSR.title; safeError.name = 'FailedToLoadModuleSSR';
safeError.name = 'FailedToLoadModuleSSR'; safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName);
safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName); safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint;
safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint; safeError.code = AstroErrorData.FailedToLoadModuleSSR.code;
safeError.code = AstroErrorData.FailedToLoadModuleSSR.code; const line = lns.findIndex((ln) => ln.includes(importName!));
const line = lns.findIndex((ln) => ln.includes(importName));
if (line !== -1) { if (line !== -1) {
const column = lns[line]?.indexOf(importName); const column = lns[line]?.indexOf(importName);
safeError.loc = { safeError.loc = {
file: path, file: path,
line: line + 1, line: line + 1,
column, column,
}; };
}
} }
} }

View file

@ -1,4 +1,4 @@
<style> <style lang="postcss">
.svelte { .svelte {
&.nested { &.nested {
color: red; color: red;

View file

@ -139,9 +139,13 @@ export async function loadFixture(inlineConfig) {
let devServer; let devServer;
return { return {
build: (opts = {}) => build(settings, { logging, telemetry, ...opts }), build: (opts = {}) => {
process.env.NODE_ENV = 'production';
return build(settings, { logging, telemetry, ...opts });
},
sync: (opts) => sync(settings, { logging, fs, ...opts }), sync: (opts) => sync(settings, { logging, fs, ...opts }),
startDevServer: async (opts = {}) => { startDevServer: async (opts = {}) => {
process.env.NODE_ENV = 'development';
devServer = await dev(settings, { logging, telemetry, ...opts }); devServer = await dev(settings, { logging, telemetry, ...opts });
config.server.host = parseAddressToHost(devServer.address.address); // update host config.server.host = parseAddressToHost(devServer.address.address); // update host
config.server.port = devServer.address.port; // update port config.server.port = devServer.address.port; // update port
@ -151,6 +155,7 @@ export async function loadFixture(inlineConfig) {
resolveUrl, resolveUrl,
fetch: (url, init) => fetch(resolveUrl(url), init), fetch: (url, init) => fetch(resolveUrl(url), init),
preview: async (opts = {}) => { preview: async (opts = {}) => {
process.env.NODE_ENV = 'production';
const previewServer = await preview(settings, { logging, telemetry, ...opts }); const previewServer = await preview(settings, { logging, telemetry, ...opts });
config.server.host = parseAddressToHost(previewServer.host); // update host config.server.host = parseAddressToHost(previewServer.host); // update host
config.server.port = previewServer.port; // update port config.server.port = previewServer.port; // update port

View file

@ -62,7 +62,7 @@
"mocha": "^9.2.2", "mocha": "^9.2.2",
"rollup-plugin-copy": "^3.4.0", "rollup-plugin-copy": "^3.4.0",
"sharp": "^0.31.0", "sharp": "^0.31.0",
"vite": "^3.0.0" "vite": "^4.0.3"
}, },
"peerDependencies": { "peerDependencies": {
"sharp": ">=0.31.0" "sharp": ">=0.31.0"

View file

@ -68,7 +68,7 @@
"remark-rehype": "^10.1.0", "remark-rehype": "^10.1.0",
"remark-shiki-twoslash": "^3.1.0", "remark-shiki-twoslash": "^3.1.0",
"remark-toc": "^8.0.1", "remark-toc": "^8.0.1",
"vite": "^3.0.0" "vite": "^4.0.3"
}, },
"engines": { "engines": {
"node": "^14.18.0 || >=16.12.0" "node": "^14.18.0 || >=16.12.0"

View file

@ -46,6 +46,6 @@
"chai": "^4.3.6", "chai": "^4.3.6",
"cheerio": "^1.0.0-rc.11", "cheerio": "^1.0.0-rc.11",
"mocha": "^9.2.2", "mocha": "^9.2.2",
"vite": "^3.0.0" "vite": "^4.0.3"
} }
} }

View file

@ -33,19 +33,17 @@
"dev": "astro-scripts dev \"src/**/*.ts\"" "dev": "astro-scripts dev \"src/**/*.ts\""
}, },
"dependencies": { "dependencies": {
"@sveltejs/vite-plugin-svelte": "^1.0.1", "@sveltejs/vite-plugin-svelte": "^2.0.2",
"postcss-load-config": "^3.1.4",
"svelte-preprocess": "^4.10.7",
"svelte2tsx": "^0.5.11" "svelte2tsx": "^0.5.11"
}, },
"devDependencies": { "devDependencies": {
"astro": "workspace:*", "astro": "workspace:*",
"astro-scripts": "workspace:*", "astro-scripts": "workspace:*",
"svelte": "^3.48.0", "svelte": "^3.54.0",
"vite": "^3.0.0" "vite": "^4.0.3"
}, },
"peerDependencies": { "peerDependencies": {
"svelte": "^3.46.4" "svelte": "^3.54.0"
}, },
"engines": { "engines": {
"node": "^14.18.0 || >=16.12.0" "node": "^14.18.0 || >=16.12.0"

View file

@ -1,7 +1,6 @@
import type { Options } from '@sveltejs/vite-plugin-svelte'; import type { Options } from '@sveltejs/vite-plugin-svelte';
import { svelte } from '@sveltejs/vite-plugin-svelte'; import { svelte, vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import type { AstroConfig, AstroIntegration, AstroRenderer } from 'astro'; import type { AstroIntegration, AstroRenderer } from 'astro';
import preprocess from 'svelte-preprocess';
import type { UserConfig } from 'vite'; import type { UserConfig } from 'vite';
function getRenderer(): AstroRenderer { function getRenderer(): AstroRenderer {
@ -15,27 +14,13 @@ function getRenderer(): AstroRenderer {
type ViteConfigurationArgs = { type ViteConfigurationArgs = {
isDev: boolean; isDev: boolean;
options?: Options | OptionsCallback; options?: Options | OptionsCallback;
postcssConfig: AstroConfig['style']['postcss'];
}; };
function getViteConfiguration({ function getViteConfiguration({ options, isDev }: ViteConfigurationArgs): UserConfig {
options,
postcssConfig,
isDev,
}: ViteConfigurationArgs): UserConfig {
const defaultOptions: Partial<Options> = { const defaultOptions: Partial<Options> = {
emitCss: true, emitCss: true,
compilerOptions: { dev: isDev, hydratable: true }, compilerOptions: { dev: isDev, hydratable: true },
preprocess: [ preprocess: [vitePreprocess()],
preprocess({
less: true,
postcss: postcssConfig,
sass: { renderSync: true },
scss: { renderSync: true },
stylus: true,
typescript: true,
}),
],
}; };
// Disable hot mode during the build // Disable hot mode during the build
@ -65,7 +50,7 @@ function getViteConfiguration({
return { return {
optimizeDeps: { optimizeDeps: {
include: ['@astrojs/svelte/client.js', 'svelte', 'svelte/internal'], include: ['@astrojs/svelte/client.js'],
exclude: ['@astrojs/svelte/server.js'], exclude: ['@astrojs/svelte/server.js'],
}, },
plugins: [svelte(resolvedOptions)], plugins: [svelte(resolvedOptions)],
@ -78,13 +63,12 @@ export default function (options?: Options | OptionsCallback): AstroIntegration
name: '@astrojs/svelte', name: '@astrojs/svelte',
hooks: { hooks: {
// Anything that gets returned here is merged into Astro Config // Anything that gets returned here is merged into Astro Config
'astro:config:setup': ({ command, updateConfig, addRenderer, config }) => { 'astro:config:setup': ({ command, updateConfig, addRenderer }) => {
addRenderer(getRenderer()); addRenderer(getRenderer());
updateConfig({ updateConfig({
vite: getViteConfiguration({ vite: getViteConfiguration({
options, options,
isDev: command === 'dev', isDev: command === 'dev',
postcssConfig: config.style.postcss,
}), }),
}); });
}, },

View file

@ -34,8 +34,8 @@
"test": "mocha --timeout 20000" "test": "mocha --timeout 20000"
}, },
"dependencies": { "dependencies": {
"@vitejs/plugin-vue": "^3.0.0", "@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^2.0.1", "@vitejs/plugin-vue-jsx": "^3.0.0",
"@vue/babel-plugin-jsx": "^1.1.1", "@vue/babel-plugin-jsx": "^1.1.1",
"@vue/compiler-sfc": "^3.2.39" "@vue/compiler-sfc": "^3.2.39"
}, },
@ -46,7 +46,7 @@
"chai": "^4.3.6", "chai": "^4.3.6",
"linkedom": "^0.14.17", "linkedom": "^0.14.17",
"mocha": "^9.2.2", "mocha": "^9.2.2",
"vite": "^3.0.0", "vite": "^4.0.3",
"vue": "^3.2.37" "vue": "^3.2.37"
}, },
"peerDependencies": { "peerDependencies": {

File diff suppressed because it is too large Load diff