Skip to content

Commit

Permalink
refactor: rename publicPath option to assetsBase
Browse files Browse the repository at this point in the history
  • Loading branch information
nilennoct committed Jun 7, 2023
1 parent 090b0cd commit 3fcd8f5
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 60 deletions.
8 changes: 5 additions & 3 deletions docs/reference/site-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,20 +222,22 @@ export default {
}
```

### publicPath
### assetsBase

- Type: `string`
- Default: `/assets/`

The base URL the site assets will be deployed at. You will need to set this if you plan to deploy your site assets to CDN. It should always end with a slash.
The base URL the site assets will be deployed at. You will need to set this if you plan to deploy your site assets to CDN. It is similar to `publicPath` in other module bundler.

The `assetsBase` is configured to `${base}assets/` by default. It should always start with a slash or a valid protocol, and always end with a slash.

::: warning
This option only takes effect in production mode.
:::

```ts
export default {
publicPath: 'https://cdn.example.com/assets/bar/'
assetsBase: 'https://cdn.example.com/assets/bar/'
}
```

Expand Down
4 changes: 2 additions & 2 deletions src/client/app/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function pathToFile(path: string): string {
// /foo/bar.html -> ./foo_bar.md
if (inBrowser) {
const base = import.meta.env.BASE_URL
const publicPath = import.meta.env.VITE_VP_PUBLIC_PATH ?? `${base}assets/`
const assetsBase = import.meta.env.VITE_VP_ASSETS_BASE ?? `${base}assets/`
pagePath =
sanitizeFileName(
pagePath.slice(base.length).replace(/\//g, '_') || 'index'
Expand All @@ -58,7 +58,7 @@ export function pathToFile(path: string): string {
: pagePath.slice(0, -3) + '_index.md'
pageHash = __VP_HASH_MAP__[pagePath.toLowerCase()]
}
pagePath = `${publicPath}${pagePath}.${pageHash}.js`
pagePath = `${assetsBase}${pagePath}.${pageHash}.js`
} else {
// ssr build uses much simpler name mapping
pagePath = `./${sanitizeFileName(
Expand Down
2 changes: 1 addition & 1 deletion src/client/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
///<reference types="vite/client"/>

interface ImportMetaEnv {
readonly VITE_VP_PUBLIC_PATH?: string
readonly VITE_VP_ASSETS_BASE?: string
}

interface ImportMeta {
Expand Down
16 changes: 8 additions & 8 deletions src/node/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import { normalizeBaseUrl, resolveConfig } from '../config'
import type { HeadConfig } from '../shared'
import { serializeFunctions } from '../utils/fnSerialize'
import {
getDefaultPublicPath,
isDefaultPublicPath,
getDefaultAssetsBase,
isDefaultAssetsBase,
normalizeAssetUrl
} from '../utils/publicPath'
} from '../utils/assetsBase'
import { bundle, failMark, okMark } from './bundle'
import { renderPage } from './render'

Expand All @@ -29,16 +29,16 @@ export async function build(
const unlinkVue = linkVue()

if (buildOptions.base) {
const shouldUpdatePublicPath = isDefaultPublicPath(
const shouldUpdateAssetsBase = isDefaultAssetsBase(
siteConfig.site.base,
siteConfig.site.publicPath
siteConfig.site.assetsBase
)

siteConfig.site.base = normalizeBaseUrl(buildOptions.base)
delete buildOptions.base

if (shouldUpdatePublicPath) {
siteConfig.site.publicPath = getDefaultPublicPath(siteConfig.site.base)
if (shouldUpdateAssetsBase) {
siteConfig.site.assetsBase = getDefaultAssetsBase(siteConfig.site.base)
}
}

Expand All @@ -47,7 +47,7 @@ export async function build(
delete buildOptions.mpa
}

process.env.VITE_VP_PUBLIC_PATH = siteConfig.site.publicPath
process.env.VITE_VP_ASSETS_BASE = siteConfig.site.assetsBase
try {
const { clientResult, serverResult, pageToHashMap } = await bundle(
siteConfig,
Expand Down
2 changes: 1 addition & 1 deletion src/node/build/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type { SiteConfig } from '../config'
import { APP_PATH } from '../alias'
import { createVitePressPlugin } from '../plugin'
import { sanitizeFileName, slash } from '../shared'
import { normalizeAssetUrl } from '../utils/publicPath'
import { normalizeAssetUrl } from '../utils/assetsBase'
import { buildMPAClient } from './buildMPAClient'
import { fileURLToPath } from 'url'
import { normalizePath } from 'vite'
Expand Down
2 changes: 1 addition & 1 deletion src/node/build/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
type SSGContext
} from '../shared'
import { deserializeFunctions } from '../utils/fnSerialize'
import { normalizeAssetUrl } from '../utils/publicPath'
import { normalizeAssetUrl } from '../utils/assetsBase'

export async function renderPage(
render: (path: string) => Promise<SSGContext>,
Expand Down
12 changes: 6 additions & 6 deletions src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
type RawConfigExports,
type SiteConfig
} from './siteConfig'
import { getDefaultPublicPath, normalizePublicPath } from './utils/publicPath'
import { getDefaultAssetsBase, normalizeAssetsBase } from './utils/assetsBase'

export * from './siteConfig'
export { resolvePages } from './plugins/dynamicRoutesPlugin'
Expand Down Expand Up @@ -213,10 +213,10 @@ export async function resolveSiteData(
userConfig = userConfig || (await resolveUserConfig(root, command, mode))[0]

const base = userConfig.base ? normalizeBaseUrl(userConfig.base) : '/'
const publicPath =
mode === 'production' && userConfig.publicPath
? normalizePublicPath(userConfig.publicPath)
: getDefaultPublicPath(base)
const assetsBase =
mode === 'production' && userConfig.assetsBase
? normalizeAssetsBase(userConfig.assetsBase)
: getDefaultAssetsBase(base)

return {
lang: userConfig.lang || 'en-US',
Expand All @@ -225,7 +225,7 @@ export async function resolveSiteData(
titleTemplate: userConfig.titleTemplate,
description: userConfig.description || 'A VitePress site',
base,
publicPath,
assetsBase,
head: resolveSiteDataHead(userConfig),
appearance: userConfig.appearance ?? true,
themeConfig: userConfig.themeConfig || {},
Expand Down
16 changes: 8 additions & 8 deletions src/node/serve/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import polka, { type IOptions } from 'polka'
import sirv, { type RequestHandler } from 'sirv'
import { resolveConfig } from '../config'
import { isExternal } from '../shared'
import { getDefaultPublicPath, isDefaultPublicPath } from '../utils/publicPath'
import { getDefaultAssetsBase, isDefaultAssetsBase } from '../utils/assetsBase'

function trimChar(str: string, char: string) {
while (str.charAt(0) === char) {
Expand Down Expand Up @@ -54,23 +54,23 @@ export async function serve(options: ServeOptions = {}) {

const server = polka({ onNoMatch })

const publicPath = site.site.publicPath
if (isExternal(publicPath)) {
const assetsBase = site.site.assetsBase
if (isExternal(assetsBase)) {
site.logger.warn(
`Using external public path (${publicPath}) will break assets serving`
`Using external assets base (${assetsBase}) will break assets serving`
)
} else if (!isDefaultPublicPath(site.site.base, publicPath)) {
const defaultPublicPath = getDefaultPublicPath(
} else if (!isDefaultAssetsBase(site.site.base, assetsBase)) {
const defaultAssetsBase = getDefaultAssetsBase(
options.base ?? site.site.base
)

// redirect non-default asset requests
server.use((req, res, next) => {
if (req.url.startsWith(publicPath)) {
if (req.url.startsWith(assetsBase)) {
res.statusCode = 307
res.setHeader(
'Location',
`${defaultPublicPath}${req.url.slice(publicPath.length)}`
`${defaultAssetsBase}${req.url.slice(assetsBase.length)}`
)
res.end()
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/node/siteConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export interface UserConfig<ThemeConfig = any>
extends?: RawConfigExports<ThemeConfig>

base?: string
publicPath?: string
assetsBase?: string
srcDir?: string
srcExclude?: string[]
outDir?: string
Expand Down
28 changes: 28 additions & 0 deletions src/node/utils/assetsBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { isExternal, type SiteData } from '../shared'

export function getDefaultAssetsBase(base: string) {
return `${base}assets/`
}

export function isDefaultAssetsBase(base: string, assetsBase: string) {
return assetsBase === getDefaultAssetsBase(base)
}

export function normalizeAssetsBase(assetsBase: string) {
// add leading slash if given `assetsBase` is not external
if (!isExternal(assetsBase)) {
assetsBase = assetsBase.replace(/^([^/])/, '/$1')
}

// add trailing slash
return assetsBase.replace(/([^/])$/, '$1/')
}

export function normalizeAssetUrl(siteData: SiteData, filename: string) {
// normalize assets only
if (filename.startsWith('assets/')) {
return `${siteData.assetsBase}${filename.slice(7)}`
}

return `${siteData.base}${filename}`
}
28 changes: 0 additions & 28 deletions src/node/utils/publicPath.ts

This file was deleted.

2 changes: 1 addition & 1 deletion types/shared.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export interface Header {

export interface SiteData<ThemeConfig = any> {
base: string
publicPath: string
assetsBase: string
cleanUrls?: boolean
lang: string
dir: string
Expand Down

0 comments on commit 3fcd8f5

Please sign in to comment.