Skip to content

feat!: move to ESM-only (CJS generation format also dropped) #448

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 48 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Static-site generation for Vue 3 on Vite.

[![NPM version](https://img.shields.io/npm/v/vite-ssg?color=a1b858)](https://www.npmjs.com/package/vite-ssg)

> ℹ️ **ESM-only from `v27.0.0` (CJS generation format also dropped).**
>
> ℹ️ **Vite 2 is supported from `v0.2.x`, Vite 1's support is discontinued.**

## Install
Expand Down Expand Up @@ -46,6 +48,48 @@ export const createApp = ViteSSG(
)
```

### How to allow Rollup tree-shake your client code

In order to allow Rollup tree-shake your client code at build time, you need to wrap you code using `import.meta.env.SSR`, that's, checking if the build is for the server: Rollup will remove the server code from the client build.

```ts
if (import.meta.env.SSR) {
// your server code will be removed in the client build
}
else {
// your client code will be removed in the server build
}
```

Alternatively, you can also use `isClient` from `ViteSSGContext` using these 3 simple rules:
1) don't destructure the `ViteSSGContext` in the `ViteSSG` function
2) don't destructure `isClient` from `ViteSSGContext` in the callback function body
3) use `isClient` from `ViteSSGContext` in the callback function body (implicit ;) )

```ts
import { ViteSSG } from 'vite-ssg'
import App from './App.vue'

export const createApp = ViteSSG(
// the root component
App,
// vue-router options
{ routes },
// previous 1) rule
(ctx) => {
// previous 2) rule
const { app, router, routes, initialState } = ctx
// previous 3) rule
if (ctx.isClient) {
// your client code
}
else {
// your server code
}
}
)
```

### Single Page SSG

For SSG of an index page only (i.e. without `vue-router`); import `vite-ssg/single-page` instead, and only install `@unhead/vue` (`npm i -D vite-ssg @unhead/vue`).
Expand Down Expand Up @@ -307,14 +351,14 @@ const { app, router, initialState, isClient, onSSRAppRendered } = ctx
const pinia = createPinia()
app.use(pinia)

if (isClient) {
pinia.state.value = (initialState.pinia) || {}
}
else {
if (import.meta.env.SSR) {
onSSRAppRendered(() => {
initialState.pinia = pinia.state.value
})
}
else {
pinia.state.value = (initialState.pinia) || {}
}
```

## Configuration
Expand Down
3 changes: 1 addition & 2 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ export default defineBuildConfig({
{ input: 'src/node', name: 'node' },
],
clean: true,
declaration: true,
declaration: 'node16',
externals: [
'vue',
'vue/server-renderer',
'vue/compiler-sfc',
],
rollup: {
emitCJS: true,
inlineDependencies: true,
},
})
File renamed without changes.
28 changes: 10 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"name": "vite-ssg",
"type": "module",
"version": "26.1.0",
"packageManager": "[email protected]",
"description": "Server-side generation for Vite",
Expand All @@ -20,29 +21,20 @@
],
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./node": {
"import": "./dist/node.mjs",
"require": "./dist/node.cjs"
},
"./single-page": {
"import": "./dist/client/single-page.mjs",
"require": "./dist/client/single-page.cjs"
}
".": "./dist/index.mjs",
"./node": "./dist/node.mjs",
"./single-page": "./dist/client/single-page.mjs"
},
"main": "dist/index.cjs",
"main": "dist/index.mjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"types": "dist/index.d.mts",
"typesVersions": {
"*": {
"single-page": [
"dist/client/single-page.d.ts"
],
"node": [
"dist/node.d.ts"
"dist/node.d.mts"
],
"single-page": [
"dist/client/single-page.d.mts"
]
}
},
Expand Down
2 changes: 1 addition & 1 deletion src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function ViteSSG(
rootContainer = '#app',
} = options ?? {}

async function createApp(_client = false, routePath?: string) {
async function createApp(routePath?: string) {
const app = import.meta.env.SSR || options?.hydration
? createSSRApp(App)
: createClientApp(App)
Expand Down
2 changes: 1 addition & 1 deletion src/client/single-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function ViteSSG(
rootContainer = '#app',
} = options ?? {}

async function createApp(_client = false) {
async function createApp() {
const app = import.meta.env.SSR || options?.hydration
? createSSRApp(App)
: createClientApp(App)
Expand Down
69 changes: 29 additions & 40 deletions src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import type { SSRContext } from 'vue/server-renderer'
import type { ViteSSGContext, ViteSSGOptions } from '../types'
import { existsSync } from 'node:fs'
import fs from 'node:fs/promises'
import { createRequire } from 'node:module'
import { dirname, isAbsolute, join, parse } from 'node:path'
import { dirname, isAbsolute, parse, resolve } from 'node:path'
import process from 'node:process'
import { pathToFileURL } from 'node:url'
import { renderDOMHead } from '@unhead/dom'
import { blue, cyan, dim, gray, green, red, yellow } from 'ansis'
import { JSDOM } from 'jsdom'
Expand All @@ -21,7 +21,7 @@ import { buildLog, getSize, routesToPaths } from './utils'

export type Manifest = Record<string, string[]>

export type CreateAppFactory = (client: boolean, routePath?: string) => Promise<ViteSSGContext<true> | ViteSSGContext<false>>
export type CreateAppFactory = (routePath?: string) => Promise<ViteSSGContext<true> | ViteSSGContext<false>>

function DefaultIncludedRoutes(paths: string[], _routes: Readonly<RouteRecordRaw[]>) {
// ignore dynamic routes
Expand All @@ -35,10 +35,10 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig

const cwd = process.cwd()
const root = config.root || cwd
const ssgOutTempFolder = join(root, '.vite-ssg-temp')
const ssgOut = join(ssgOutTempFolder, Math.random().toString(36).substring(2, 12))
const ssgOutTempFolder = resolve(root, '.vite-ssg-temp')
const ssgOut = resolve(ssgOutTempFolder, Math.random().toString(36).substring(2, 12))
const outDir = config.build.outDir || 'dist'
const out = isAbsolute(outDir) ? outDir : join(root, outDir)
const out = isAbsolute(outDir) ? outDir : resolve(root, outDir)

const mergedOptions = Object.assign({}, config.ssgOptions || {}, ssgOptions)
const {
Expand All @@ -52,7 +52,6 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
onFinished,
dirStyle = 'flat',
includeAllRoutes = false,
format = 'esm',
concurrency = 20,
rootContainerId = 'app',
base,
Expand All @@ -71,7 +70,7 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
ssrManifest: true,
rollupOptions: {
input: {
app: join(root, './index.html'),
app: resolve(root, './index.html'),
},
},
},
Expand All @@ -97,15 +96,10 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
minify: false,
cssCodeSplit: false,
rollupOptions: {
output: format === 'esm'
? {
entryFileNames: '[name].mjs',
format: 'esm',
}
: {
entryFileNames: '[name].cjs',
format: 'cjs',
},
output: {
entryFileNames: '[name].mjs',
format: 'esm',
},
},
},
mode: config.mode,
Expand All @@ -114,22 +108,17 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
},
}))

const prefix = (format === 'esm' && process.platform === 'win32') ? 'file://' : ''
const ext = format === 'esm' ? '.mjs' : '.cjs'

/**
* `join('file://')` will be equal to `'file:\'`, which is not the correct file protocol and will fail to be parsed under bun.
* It is changed to '+' splicing here.
*/
const serverEntry = prefix + join(ssgOut, parse(ssrEntry).name + ext).replace(/\\/g, '/')

const _require = createRequire(import.meta.url)
const serverEntry = pathToFileURL(resolve(ssgOut, `${parse(ssrEntry).name}.mjs`)).href
const {
createApp,
includedRoutes: serverEntryIncludedRoutes,
}: {
createApp: CreateAppFactory
includedRoutes: ViteSSGOptions['includedRoutes']
} = await import(serverEntry)

const { createApp, includedRoutes: serverEntryIncludedRoutes }: { createApp: CreateAppFactory, includedRoutes: ViteSSGOptions['includedRoutes'] } = format === 'esm'
? await import(serverEntry)
: _require(serverEntry)
const includedRoutes = serverEntryIncludedRoutes || configIncludedRoutes
const { routes } = await createApp(false)
const { routes } = await createApp()

let routesPaths = includeAllRoutes
? routesToPaths(routes)
Expand All @@ -151,11 +140,11 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
path: _ssrManifestPath,
content: ssrManifestRaw,
} = await readFiles(
join(out, '.vite', 'ssr-manifest.json'), // Vite 5
join(out, 'ssr-manifest.json'), // Vite 4 and below
resolve(out, '.vite', 'ssr-manifest.json'), // Vite 5
resolve(out, 'ssr-manifest.json'), // Vite 4 and below
)
const ssrManifest: Manifest = JSON.parse(ssrManifestRaw)
let indexHTML = await fs.readFile(join(out, 'index.html'), 'utf-8')
let indexHTML = await fs.readFile(resolve(out, 'index.html'), 'utf-8')
indexHTML = rewriteScripts(indexHTML, script)

const { renderToString }: typeof import('vue/server-renderer') = await import('vue/server-renderer')
Expand All @@ -165,7 +154,7 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
for (const route of routesPaths) {
queue.add(async () => {
try {
const appCtx = await createApp(false, route) as ViteSSGContext<true>
const appCtx = await createApp(route) as ViteSSGContext<true>
const { app, router, head, initialState, triggerOnSSRAppRendered, transformState = serializeState } = appCtx

if (router) {
Expand Down Expand Up @@ -208,11 +197,11 @@ export async function build(ssgOptions: Partial<ViteSSGOptions> = {}, viteConfig
: route).replace(/^\//g, '')}.html`

const filename = dirStyle === 'nested'
? join(route.replace(/^\//g, ''), 'index.html')
? resolve(route.replace(/^\//g, ''), 'index.html')
: relativeRouteFile

await fs.mkdir(join(out, dirname(filename)), { recursive: true })
await fs.writeFile(join(out, filename), formatted, 'utf-8')
await fs.mkdir(resolve(out, dirname(filename)), { recursive: true })
await fs.writeFile(resolve(out, filename), formatted, 'utf-8')
config.logger.info(
`${dim(`${outDir}/`)}${cyan(filename.padEnd(15, ' '))} ${dim(getSize(formatted))}`,
)
Expand Down Expand Up @@ -251,7 +240,7 @@ async function detectEntry(root: string) {
// pick the first script tag of type module as the entry
// eslint-disable-next-line regexp/no-super-linear-backtracking
const scriptSrcReg = /<script.*?src=["'](.+?)["'](?!<).*>\s*<\/script>/gi
const html = await fs.readFile(join(root, 'index.html'), 'utf-8')
const html = await fs.readFile(resolve(root, 'index.html'), 'utf-8')
const scripts = [...html.matchAll(scriptSrcReg)]
const [, entry] = scripts.find((matchResult) => {
const [script] = matchResult
Expand All @@ -264,7 +253,7 @@ async function detectEntry(root: string) {
async function resolveAlias(config: ResolvedConfig, entry: string) {
const resolver = config.createResolver()
const result = await resolver(entry, config.root)
return result || join(config.root, entry)
return result || resolve(config.root, entry)
}

function rewriteScripts(indexHTML: string, mode?: string) {
Expand Down
7 changes: 0 additions & 7 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,6 @@ export interface ViteSSGOptions {
*/
script?: 'sync' | 'async' | 'defer' | 'async defer'

/**
* Build format.
*
* @default 'esm'
*/
format?: 'esm' | 'cjs'

/**
* The path of the main entry file (relative to the project root).
*
Expand Down