From 7ae37941e1f50dea6711696b55fc694ad2e9897c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20T=C3=A1vora?= Date: Wed, 21 Jul 2021 13:06:44 +0100 Subject: [PATCH] fix: allow user to add Vitepress configuration to ESM packages If users have a `type: module` entry in their `package.json`, they could not use VitePress with a `config.js` file. This change makes it so that `config.cjs` is searched before `config.js`. Node's 'require' function allows files with such extensions to be loaded even from within an ES module project. * docs/guide/configuration.md: Mention config.cjs * src/node/config.ts: Consider config.cjs --- docs/guide/configuration.md | 5 +++++ src/node/config.ts | 25 ++++++++++++------------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 7dc8d1e00189..046d7dee879c 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -20,4 +20,9 @@ module.exports = { } ``` +::: warning +If your project uses [ES modules](https://nodejs.org/api/esm.html), +name this file `.vitepress/config.cjs` instead. +::: + Check out the [Config Reference](/config/basics) for a full list of options. diff --git a/src/node/config.ts b/src/node/config.ts index ec2ff48ab49f..7178aba4eac9 100644 --- a/src/node/config.ts +++ b/src/node/config.ts @@ -111,20 +111,19 @@ export async function resolveConfig( return config } -export async function resolveUserConfig(root: string) { - // load user config - const configPath = resolve(root, 'config.js') - const hasUserConfig = await fs.pathExists(configPath) - // always delete cache first before loading config - delete require.cache[configPath] - const userConfig: UserConfig = hasUserConfig ? require(configPath) : {} - if (hasUserConfig) { - debug(`loaded config at ${chalk.yellow(configPath)}`) - } else { - debug(`no config file found.`) +export async function resolveUserConfig(root: string): Promise { + for (const name of ['config.cjs', 'config.js']) { + // load user config + const configPath = resolve(root, name) + // always delete cache first before loading config + delete require.cache[configPath] + if (await fs.pathExists(configPath)) { + debug(`loaded config at ${chalk.yellow(configPath)}`) + return require(configPath) + } } - - return userConfig + debug(`no config file found.`) + return {} } export async function resolveSiteData(