Skip to content

Commit

Permalink
Upgrade to Vite 4 (#5685)
Browse files Browse the repository at this point in the history
* Upgrade Vite 4

* Simplify Svelte preprocess setup

* Upgrade rollup

* Fix tests

* Fix wrong changeset target

* Fix error tests

* Set NODE_ENV default
  • Loading branch information
bluwy authored Jan 3, 2023
1 parent 5007bc7 commit f6cf92b
Show file tree
Hide file tree
Showing 21 changed files with 384 additions and 3,506 deletions.
7 changes: 7 additions & 0 deletions .changeset/new-lies-guess.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/spotty-bees-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/svelte': major
---

Simplify Svelte preprocess setup. `<style lang="postcss">` is now required if using PostCSS inside style tags.
26 changes: 0 additions & 26 deletions packages/astro/e2e/error-react-spectrum.test.js

This file was deleted.

This file was deleted.

12 changes: 0 additions & 12 deletions packages/astro/e2e/fixtures/error-react-spectrum/package.json

This file was deleted.

This file was deleted.

6 changes: 3 additions & 3 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@
"recast": "^0.20.5",
"rehype": "^12.0.1",
"resolve": "^1.22.0",
"rollup": "^2.79.1",
"semver": "^7.3.7",
"shiki": "^0.11.1",
"sirv": "^2.0.2",
Expand All @@ -168,8 +167,8 @@
"typescript": "*",
"unist-util-visit": "^4.1.0",
"vfile": "^5.3.2",
"vite": "~3.2.5",
"vitefu": "^0.2.1",
"vite": "^4.0.3",
"vitefu": "^0.2.4",
"yargs-parser": "^21.0.1",
"zod": "^3.17.3"
},
Expand Down Expand Up @@ -207,6 +206,7 @@
"rehype-slug": "^5.0.1",
"rehype-toc": "^3.0.2",
"remark-code-titles": "^0.1.2",
"rollup": "^3.9.0",
"sass": "^1.52.2",
"srcset-parse": "^1.1.0",
"unified": "^10.1.2"
Expand Down
5 changes: 5 additions & 0 deletions packages/astro/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
cwd: root,
flags,
Expand Down
3 changes: 1 addition & 2 deletions packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import markdownVitePlugin from '../vite-plugin-markdown/index.js';
import astroScannerPlugin from '../vite-plugin-scanner/index.js';
import astroScriptsPlugin from '../vite-plugin-scripts/index.js';
import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js';
import { createCustomViteLogger } from './errors/dev/index.js';
import { resolveDependency } from './util.js';

interface CreateViteOptions {
Expand Down Expand Up @@ -197,7 +196,7 @@ export async function createVite(
sortPlugins(result.plugins);
}

result.customLogger = createCustomViteLogger(result.logLevel ?? 'warn');
result.customLogger = vite.createLogger(result.logLevel ?? 'warn');

return result;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/errors/dev/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { collectErrorMetadata } from './utils.js';
export { createCustomViteLogger, enhanceViteSSRError, getViteErrorPayload } from './vite.js';
export { enhanceViteSSRError, getViteErrorPayload } from './vite.js';
11 changes: 0 additions & 11 deletions packages/astro/src/core/errors/dev/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ import { normalizeLF } from '../utils.js';

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.
* Useful for consistent reporting regardless of where the error surfaced from.
Expand Down Expand Up @@ -135,12 +130,6 @@ ${
See https://docs.astro.build/en/guides/troubleshooting/#document-or-window-is-not-defined for more information.
`;
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;
}
Expand Down
58 changes: 20 additions & 38 deletions packages/astro/src/core/errors/dev/vite.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,12 @@
import * as fs from 'fs';
import { getHighlighter } from 'shiki';
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 { AstroErrorData } from '../errors-data.js';
import { type ErrorWithMetadata } from '../errors.js';
import type { ErrorWithMetadata } from '../errors.js';
import { createSafeError } from '../utils.js';
import { incompatPackageExp, 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;
}
import { renderErrorMarkdown } from './utils.js';

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
Expand All @@ -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
// 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)) {
const importName = safeError.message.split('for ssr:').at(1)?.trim();
if (importName) {
safeError.title = AstroErrorData.FailedToLoadModuleSSR.title;
safeError.name = 'FailedToLoadModuleSSR';
safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName);
safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint;
safeError.code = AstroErrorData.FailedToLoadModuleSSR.code;
const line = lns.findIndex((ln) => ln.includes(importName));

if (line !== -1) {
const column = lns[line]?.indexOf(importName);

safeError.loc = {
file: path,
line: line + 1,
column,
};
}
let importName: string | undefined;
if ((importName = safeError.message.match(/Failed to load url (.*?) \(resolved id:/)?.[1])) {
safeError.title = AstroErrorData.FailedToLoadModuleSSR.title;
safeError.name = 'FailedToLoadModuleSSR';
safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName);
safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint;
safeError.code = AstroErrorData.FailedToLoadModuleSSR.code;
const line = lns.findIndex((ln) => ln.includes(importName!));

if (line !== -1) {
const column = lns[line]?.indexOf(importName);

safeError.loc = {
file: path,
line: line + 1,
column,
};
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<style>
<style lang="postcss">
.svelte {
&.nested {
color: red;
Expand Down
7 changes: 6 additions & 1 deletion packages/astro/test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,13 @@ export async function loadFixture(inlineConfig) {
let devServer;

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 }),
startDevServer: async (opts = {}) => {
process.env.NODE_ENV = 'development';
devServer = await dev(settings, { logging, telemetry, ...opts });
config.server.host = parseAddressToHost(devServer.address.address); // update host
config.server.port = devServer.address.port; // update port
Expand All @@ -151,6 +155,7 @@ export async function loadFixture(inlineConfig) {
resolveUrl,
fetch: (url, init) => fetch(resolveUrl(url), init),
preview: async (opts = {}) => {
process.env.NODE_ENV = 'production';
const previewServer = await preview(settings, { logging, telemetry, ...opts });
config.server.host = parseAddressToHost(previewServer.host); // update host
config.server.port = previewServer.port; // update port
Expand Down
2 changes: 1 addition & 1 deletion packages/integrations/image/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"mocha": "^9.2.2",
"rollup-plugin-copy": "^3.4.0",
"sharp": "^0.31.0",
"vite": "^3.0.0"
"vite": "^4.0.3"
},
"peerDependencies": {
"sharp": ">=0.31.0"
Expand Down
2 changes: 1 addition & 1 deletion packages/integrations/mdx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"remark-rehype": "^10.1.0",
"remark-shiki-twoslash": "^3.1.0",
"remark-toc": "^8.0.1",
"vite": "^3.0.0"
"vite": "^4.0.3"
},
"engines": {
"node": "^14.18.0 || >=16.12.0"
Expand Down
2 changes: 1 addition & 1 deletion packages/integrations/netlify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@
"chai": "^4.3.6",
"cheerio": "^1.0.0-rc.11",
"mocha": "^9.2.2",
"vite": "^3.0.0"
"vite": "^4.0.3"
}
}
10 changes: 4 additions & 6 deletions packages/integrations/svelte/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,17 @@
"dev": "astro-scripts dev \"src/**/*.ts\""
},
"dependencies": {
"@sveltejs/vite-plugin-svelte": "^1.0.1",
"postcss-load-config": "^3.1.4",
"svelte-preprocess": "^4.10.7",
"@sveltejs/vite-plugin-svelte": "^2.0.2",
"svelte2tsx": "^0.5.11"
},
"devDependencies": {
"astro": "workspace:*",
"astro-scripts": "workspace:*",
"svelte": "^3.48.0",
"vite": "^3.0.0"
"svelte": "^3.54.0",
"vite": "^4.0.3"
},
"peerDependencies": {
"svelte": "^3.46.4"
"svelte": "^3.54.0"
},
"engines": {
"node": "^14.18.0 || >=16.12.0"
Expand Down
28 changes: 6 additions & 22 deletions packages/integrations/svelte/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { Options } from '@sveltejs/vite-plugin-svelte';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import type { AstroConfig, AstroIntegration, AstroRenderer } from 'astro';
import preprocess from 'svelte-preprocess';
import { svelte, vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import type { AstroIntegration, AstroRenderer } from 'astro';
import type { UserConfig } from 'vite';

function getRenderer(): AstroRenderer {
Expand All @@ -15,27 +14,13 @@ function getRenderer(): AstroRenderer {
type ViteConfigurationArgs = {
isDev: boolean;
options?: Options | OptionsCallback;
postcssConfig: AstroConfig['style']['postcss'];
};

function getViteConfiguration({
options,
postcssConfig,
isDev,
}: ViteConfigurationArgs): UserConfig {
function getViteConfiguration({ options, isDev }: ViteConfigurationArgs): UserConfig {
const defaultOptions: Partial<Options> = {
emitCss: true,
compilerOptions: { dev: isDev, hydratable: true },
preprocess: [
preprocess({
less: true,
postcss: postcssConfig,
sass: { renderSync: true },
scss: { renderSync: true },
stylus: true,
typescript: true,
}),
],
preprocess: [vitePreprocess()],
};

// Disable hot mode during the build
Expand Down Expand Up @@ -65,7 +50,7 @@ function getViteConfiguration({

return {
optimizeDeps: {
include: ['@astrojs/svelte/client.js', 'svelte', 'svelte/internal'],
include: ['@astrojs/svelte/client.js'],
exclude: ['@astrojs/svelte/server.js'],
},
plugins: [svelte(resolvedOptions)],
Expand All @@ -78,13 +63,12 @@ export default function (options?: Options | OptionsCallback): AstroIntegration
name: '@astrojs/svelte',
hooks: {
// 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());
updateConfig({
vite: getViteConfiguration({
options,
isDev: command === 'dev',
postcssConfig: config.style.postcss,
}),
});
},
Expand Down
Loading

0 comments on commit f6cf92b

Please sign in to comment.