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.

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

Loading…
Cancel
Save