Skip to content

Commit

Permalink
[nextra] support nextConfig.distDir (#1089)
Browse files Browse the repository at this point in the history
* support `nextConfig.distDir`

* fix
  • Loading branch information
dimaMachina committed Dec 17, 2022
1 parent e34eff4 commit b2fc168
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 47 deletions.
5 changes: 5 additions & 0 deletions .changeset/thin-bulldogs-enjoy.md
@@ -0,0 +1,5 @@
---
'nextra': patch
---

support `nextConfig.distDir`
3 changes: 2 additions & 1 deletion examples/swr-site/next.config.js
Expand Up @@ -5,14 +5,15 @@ const withNextra = require("nextra")({
codeblocks: true,
},
staticImage: true,
defaultShowCopyCode: true
defaultShowCopyCode: true,
});

module.exports = withNextra({
i18n: {
locales: ["en-US", "es-ES", "ja", "ko", "ru", "zh-CN"],
defaultLocale: "en-US",
},
distDir: "./.next", // Nextra supports custom `nextConfig.distDir`
redirects: () => {
return [
// {
Expand Down
4 changes: 0 additions & 4 deletions packages/nextra/src/constants.ts
Expand Up @@ -28,8 +28,4 @@ export const MARKDOWN_EXTENSIONS = ['md', 'mdx'] as const

export const PUBLIC_DIR = path.join(CWD, 'public')

export const CACHE_DIR = path.join(CWD, '.next', 'cache')

export const ASSET_DIR = path.join(CWD, '.next', 'static', 'chunks')

export const EXTERNAL_URL_REGEX = /^https?:\/\//
56 changes: 37 additions & 19 deletions packages/nextra/src/content-dump.ts
@@ -1,24 +1,19 @@
import path from 'node:path'
import fs from 'graceful-fs'
import { existsSync } from './file-system'
import { ASSET_DIR, CACHE_DIR } from './constants'
import { CWD } from './constants'

let cacheDir: string
let assetDir: string
let cacheDirExist = false

const asset: { [locale: string]: any } = Object.create(null)
const cached = new Map<string, boolean>()

if (!existsSync(ASSET_DIR)) {
fs.mkdirSync(ASSET_DIR, { recursive: true })
}

const cacheDirExist = existsSync(CACHE_DIR)
if (!cacheDirExist) {
fs.mkdirSync(CACHE_DIR, { recursive: true })
}

function initFromCache(filename: string) {
if (!cached.has(filename)) {
try {
const content = fs.readFileSync(path.join(ASSET_DIR, filename), 'utf8')
const content = fs.readFileSync(path.join(assetDir, filename), 'utf8')
cached.set(filename, true)
return JSON.parse(content)
} catch {
Expand All @@ -32,13 +27,18 @@ export function addPage({
locale,
route,
title,
structurizedData
structurizedData,
distDir
}: {
locale: string
route: string
title: string
structurizedData: any
distDir?: string
}): void {
if (!cacheDir || !assetDir) {
initConfig(distDir)
}
const dataFilename = `nextra-data-${locale}.json`

asset[locale] ||= initFromCache(dataFilename)
Expand All @@ -51,23 +51,41 @@ export function addPage({
// @TODO: introduce mutex lock, or only generate the asset when finishing the
// entire build.
const content = JSON.stringify(asset[locale])
fs.writeFileSync(path.join(ASSET_DIR, dataFilename), content)
fs.writeFileSync(path.join(CACHE_DIR, dataFilename), content)
fs.writeFileSync(path.join(assetDir, dataFilename), content)
fs.writeFileSync(path.join(cacheDir, dataFilename), content)
}

export function initConfig(distDir = '.next') {
cacheDir = path.join(CWD, distDir, 'cache')
assetDir = path.join(CWD, distDir, 'static', 'chunks')
}

// Copy cached data to the asset directory.
export function restoreCache(): void {
export function restoreCache(distDir?: string): void {
if (!cacheDir || !assetDir) {
initConfig(distDir)
if (!existsSync(assetDir)) {
fs.mkdirSync(assetDir, { recursive: true })
}

cacheDirExist = existsSync(cacheDir)
if (!cacheDirExist) {
fs.mkdirSync(cacheDir, { recursive: true })
}
}

if (!cacheDirExist) {
return
}
if (!existsSync(ASSET_DIR)) {
fs.mkdirSync(ASSET_DIR, { recursive: true })

if (!existsSync(assetDir)) {
fs.mkdirSync(assetDir, { recursive: true })
}

const files = fs.readdirSync(CACHE_DIR)
const files = fs.readdirSync(cacheDir)
for (const file of files) {
if (file.startsWith('nextra-data-')) {
fs.copyFileSync(path.join(CACHE_DIR, file), path.join(ASSET_DIR, file))
fs.copyFileSync(path.join(cacheDir, file), path.join(assetDir, file))
}
}
}
14 changes: 3 additions & 11 deletions packages/nextra/src/file-system.ts
@@ -1,17 +1,9 @@
import fs from 'graceful-fs'
import { findPagesDir } from 'next/dist/lib/find-pages-dir.js'
import { findPagesDir, existsSync } from 'next/dist/lib/find-pages-dir.js'
import { CWD } from './constants'

export const existsSync = (filePath: string): boolean => {
try {
fs.statSync(filePath)
return true
} catch {
return false
}
}
export { existsSync }

export const findPagesDirectory = (): string => {
export function findPagesDirectory(): string {
const res = findPagesDir(CWD, false)
return (
res.pagesDir || // next v13
Expand Down
14 changes: 7 additions & 7 deletions packages/nextra/src/index.js
Expand Up @@ -21,7 +21,10 @@ const nextra = (...config) =>
: config[0]
)

const nextraPlugin = new NextraPlugin(nextraConfig)
const nextraPlugin = new NextraPlugin({
...nextraConfig,
distDir: nextConfig.distDir
})

if (nextConfig.i18n?.locales) {
console.log(
Expand All @@ -44,7 +47,8 @@ const nextra = (...config) =>
locales: nextConfig.i18n?.locales || [DEFAULT_LOCALE],
defaultLocale: nextConfig.i18n?.defaultLocale || DEFAULT_LOCALE,
pageMapCache,
newNextLinkBehavior: nextConfig.experimental?.newNextLinkBehavior
newNextLinkBehavior: nextConfig.experimental?.newNextLinkBehavior,
distDir: nextConfig.distDir
}

config.module.rules.push(
Expand Down Expand Up @@ -78,11 +82,7 @@ const nextra = (...config) =>
}
)

if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options)
}

return config
return nextConfig.webpack?.(config, options) || config
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions packages/nextra/src/loader.ts
Expand Up @@ -71,7 +71,8 @@ async function loader(
readingTime: _readingTime,
mdxOptions,
pageMapCache,
newNextLinkBehavior
newNextLinkBehavior,
distDir
} = context.getOptions()

context.cacheable(true)
Expand Down Expand Up @@ -158,7 +159,8 @@ export default MDXContent`.trimStart()
locale: locale || DEFAULT_LOCALE,
route,
title,
structurizedData
structurizedData,
distDir
})
}
indexContentEmitted.add(mdxPath)
Expand Down
7 changes: 4 additions & 3 deletions packages/nextra/src/plugin.ts
Expand Up @@ -163,15 +163,16 @@ export class PageMapCache {
export const pageMapCache = new PageMapCache()

export class NextraPlugin {
constructor(private config: NextraConfig) {}
constructor(private config: NextraConfig & { distDir?: string }) {}

apply(compiler: Compiler) {
compiler.hooks.beforeCompile.tapAsync(
'NextraPlugin',
async (_, callback) => {
if (this.config?.flexsearch) {
const { flexsearch, distDir } = this.config
if (flexsearch) {
// Restore the search data from the cache.
restoreCache()
restoreCache(distDir)
}
const PAGES_DIR = findPagesDirectory()
const result = await collectFiles(PAGES_DIR)
Expand Down
1 change: 1 addition & 0 deletions packages/nextra/src/types.ts
Expand Up @@ -15,6 +15,7 @@ export interface LoaderOptions extends NextraConfig {
defaultLocale: string
pageMapCache: PageMapCache
newNextLinkBehavior?: boolean
distDir?: string
}

export interface Folder<FileType = PageMapItem> {
Expand Down

1 comment on commit b2fc168

@vercel
Copy link

@vercel vercel bot commented on b2fc168 Dec 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.