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
pull/339/head
João Távora 4 years ago
parent aa9f9094b5
commit 7ae37941e1

@ -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. Check out the [Config Reference](/config/basics) for a full list of options.

@ -111,20 +111,19 @@ export async function resolveConfig(
return config return config
} }
export async function resolveUserConfig(root: string) { export async function resolveUserConfig(root: string): Promise<UserConfig> {
// load user config for (const name of ['config.cjs', 'config.js']) {
const configPath = resolve(root, 'config.js') // load user config
const hasUserConfig = await fs.pathExists(configPath) const configPath = resolve(root, name)
// always delete cache first before loading config // always delete cache first before loading config
delete require.cache[configPath] delete require.cache[configPath]
const userConfig: UserConfig = hasUserConfig ? require(configPath) : {} if (await fs.pathExists(configPath)) {
if (hasUserConfig) { debug(`loaded config at ${chalk.yellow(configPath)}`)
debug(`loaded config at ${chalk.yellow(configPath)}`) return require(configPath)
} else { }
debug(`no config file found.`)
} }
debug(`no config file found.`)
return userConfig return {}
} }
export async function resolveSiteData( export async function resolveSiteData(

Loading…
Cancel
Save