Load configs with Vite when loading with Proload fails (#4112)

* 4078 breaking test

* Use Vite for loading the config

* Try it

* Fallback to loading with Vite only when needed

* Remove console.error

* Remove extra console.log

* Add a changeset

* Use middlewareMode
This commit is contained in:
Matthew Phillips 2022-08-02 08:08:28 -04:00 committed by GitHub
parent 10a8fa5dcd
commit e33fc9bc46
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 80 additions and 33 deletions

View file

@ -0,0 +1,6 @@
---
'astro': patch
'@astrojs/mdx': patch
---
Fix MDX working with a ts config file

View file

@ -16,6 +16,7 @@ import { z } from 'zod';
import { LogOptions } from './logger/core.js';
import { appendForwardSlash, prependForwardSlash, trimSlashes } from './path.js';
import { arraify, isObject } from './util.js';
import * as vite from 'vite';
load.use([loadTypeScript]);
@ -409,10 +410,13 @@ export async function resolveConfigURL(
const flags = resolveFlags(configOptions.flags || {});
let userConfigPath: string | undefined;
if (flags?.config) {
userConfigPath = /^\.*\//.test(flags.config) ? flags.config : `./${flags.config}`;
userConfigPath = fileURLToPath(new URL(userConfigPath, `file://${root}/`));
}
// Resolve config file path using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
const configPath = await resolve('astro', {
@ -447,21 +451,7 @@ export async function openConfig(configOptions: LoadConfigOptions): Promise<Open
);
}
// Automatically load config file using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
let config;
try {
config = await load('astro', {
mustExist: !!userConfigPath,
cwd: root,
filePath: userConfigPath,
});
} catch (err) {
if (err instanceof ProloadError && flags.config) {
throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
}
throw err;
}
const config = await tryLoadConfig(configOptions, flags, userConfigPath, root);
if (config) {
userConfig = config.value;
userConfigPath = config.filePath;
@ -483,6 +473,52 @@ export async function openConfig(configOptions: LoadConfigOptions): Promise<Open
};
}
interface TryLoadConfigResult {
value: Record<string, any>;
filePath?: string;
}
async function tryLoadConfig(configOptions: LoadConfigOptions, flags: CLIFlags, userConfigPath: string | undefined, root: string): Promise<TryLoadConfigResult | undefined> {
try {
// Automatically load config file using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
const config = await load('astro', {
mustExist: !!userConfigPath,
cwd: root,
filePath: userConfigPath,
});
return config as TryLoadConfigResult;
} catch(e) {
if (e instanceof ProloadError && flags.config) {
throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
}
const configURL = await resolveConfigURL(configOptions);
if(!configURL) {
throw e;
}
// Fallback to use Vite DevServer
const viteServer = await vite.createServer({
server: { middlewareMode: true, hmr: false },
appType: 'custom'
});
try {
const mod = await viteServer.ssrLoadModule(fileURLToPath(configURL));
if(mod?.default) {
return {
value: mod.default,
filePath: fileURLToPath(configURL),
};
};
} finally {
await viteServer.close();
}
}
}
/**
* Attempt to load an `astro.config.mjs` file
* @deprecated
@ -500,21 +536,7 @@ export async function loadConfig(configOptions: LoadConfigOptions): Promise<Astr
);
}
// Automatically load config file using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
let config;
try {
config = await load('astro', {
mustExist: !!userConfigPath,
cwd: root,
filePath: userConfigPath,
});
} catch (err) {
if (err instanceof ProloadError && flags.config) {
throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
}
throw err;
}
const config = await tryLoadConfig(configOptions, flags, userConfigPath, root);
if (config) {
userConfig = config.value;
}

View file

@ -52,7 +52,7 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
// Workarounds tried:
// - "import * as remarkShikiTwoslash"
// - "import { default as remarkShikiTwoslash }"
(remarkShikiTwoslash as any).default,
(remarkShikiTwoslash as any).default ?? remarkShikiTwoslash,
config.markdown.shikiConfig,
]);
rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);

View file

@ -0,0 +1,5 @@
import mdx from '@astrojs/mdx';
export default {
integrations: [mdx()]
}

View file

@ -0,0 +1,7 @@
{
"name": "@test/mdx-page",
"dependencies": {
"astro": "workspace:*",
"@astrojs/mdx": "workspace:*"
}
}

View file

@ -9,8 +9,7 @@ describe('MDX Page', () => {
before(async () => {
fixture = await loadFixture({
root: new URL('./fixtures/mdx-page/', import.meta.url),
integrations: [mdx()],
root: new URL('./fixtures/mdx-page/', import.meta.url)
});
});

View file

@ -2231,6 +2231,14 @@ importers:
reading-time: 1.5.0
remark-toc: 8.0.1
packages/integrations/mdx/test/fixtures/mdx-page:
specifiers:
'@astrojs/mdx': workspace:*
astro: workspace:*
dependencies:
'@astrojs/mdx': link:../../..
astro: link:../../../../../astro
packages/integrations/netlify:
specifiers:
'@astrojs/webapi': ^0.12.0