Skip to content

Commit

Permalink
fix: fixed manifest being undefined under ssr or standalone env
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed Oct 30, 2023
1 parent 25e470e commit 743e58f
Show file tree
Hide file tree
Showing 22 changed files with 201 additions and 151 deletions.
10 changes: 1 addition & 9 deletions migration-v2.0.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,7 @@ html = injectScriptsToHtml(html, (manifest) => [
])
```

2. node环境中,也可以使用 `getManifest` 获取manifest

```ts
import { getManifest } from 'vite-plugin-public-typescript'

console.log(getManifest(), 'manifest')
```

3. 在业务源码中,使用 `vite-plugin-public-typescript/client` 引入 manifest
2. 在业务源码中,使用 `vite-plugin-public-typescript/client` 引入 manifest
```ts
import { manifest } from 'vite-plugin-public-typescript/client'

Expand Down
4 changes: 3 additions & 1 deletion playground/spa-file-mode/__tests__/file-mode.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { listFiles, readFile } from '~utils'
import path from 'node:path'
import { beforeAll, describe, expect, test } from 'vitest'

const manifestPath = 'node_modules/.vite-plugin-public-typescript/manifest.json'

describe('file-mode', () => {
let jsFiles: string[]
let manifest: string

beforeAll(() => {
try {
manifest = readFile('public-typescript/manifest.json')
manifest = readFile(manifestPath)
jsFiles = listFiles('public/out')
} catch {}
})
Expand Down
2 changes: 1 addition & 1 deletion playground/ssr/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<title>ssr playground</title>
</head>

<body>
Expand Down
2 changes: 1 addition & 1 deletion playground/ssr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"build": "npm run build:client && npm run build:server",
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --ssr src/entry-server.tsx --outDir dist/server",
"generate": "vite build --outDir dist/static && npm run build:server && node prerender",
"serve": "NODE_ENV=production node server",
"debug": "node --inspect-brk server"
},
Expand All @@ -25,6 +24,7 @@
"compression": "^1.7.4",
"express": "^4.18.2",
"serve-static": "^1.15.0",
"tsx": "^3.14.0",
"vite": "^4.5.0"
}
}
33 changes: 0 additions & 33 deletions playground/ssr/prerender.js

This file was deleted.

20 changes: 10 additions & 10 deletions playground/ssr/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import express from 'express'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { getManifest, injectScriptsToHtml } from 'vite-plugin-public-typescript'
import { injectScriptsToHtml } from 'vite-plugin-public-typescript'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

const isTest = process.env.VITEST

process.env.MY_CUSTOM_SECRET = 'API_KEY_qwertyuiop'
process.env.__Manifest_Path__ = __dirname

export async function createServer(root = process.cwd(), isProd = process.env.NODE_ENV === 'production', hmrPort) {
const resolve = (p) => path.resolve(__dirname, p)
Expand Down Expand Up @@ -76,14 +77,11 @@ export async function createServer(root = process.cwd(), isProd = process.env.NO

let html = template.replace(`<!--app-html-->`, appHtml)

console.log(getManifest(), 'manifest')

html = injectScriptsToHtml(html, (manifest) => [
{
attrs: {
src: manifest.ssr,
},
injectTo: 'head-prepend',
},
])

Expand All @@ -98,8 +96,10 @@ export async function createServer(root = process.cwd(), isProd = process.env.NO
return { app, vite, hmrPort }
}

const port = process.env.PORT || 5173
const { app } = await createServer()
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
if (!isTest) {
const port = process.env.PORT || 5173
const { app } = await createServer()
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
}
2 changes: 1 addition & 1 deletion playground/ssr/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from 'vite'
import { publicTypescript } from 'vite-plugin-public-typescript'

export default defineConfig({
plugins: [react(), publicTypescript({ destination: 'memory' })],
plugins: [react(), publicTypescript()],
build: {
minify: false,
},
Expand Down
25 changes: 25 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/node/helper/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import createDebug from 'debug'
import { type BuildResult, type Plugin, build as esbuild } from 'esbuild'
import path from 'node:path'
import colors from 'picocolors'
import { type ResolvedConfig } from 'vite'
import { globalConfig } from '../global-config'
import { type BaseCacheProcessor } from '../processor/BaseCacheProcessor'
Expand Down Expand Up @@ -88,7 +89,7 @@ export async function esbuildTypescript(buildOptions: IBuildOptions) {

debug('esbuild success:', filePath)
} catch (error) {
console.error(`[${pkgName}]`, error)
console.error(colors.red(`[${pkgName}] `), error)
return
}

Expand Down
11 changes: 11 additions & 0 deletions src/node/helper/default-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { type OptionsTypeWithDefault } from './utils'

export const DEFAULT_OPTIONS: OptionsTypeWithDefault = {
destination: 'memory',
esbuildOptions: {},
hash: true,
inputDir: 'public-typescript',
manifestName: 'manifest',
outputDir: '/',
cacheDir: 'node_modules/.vite-plugin-public-typescript',
}
6 changes: 4 additions & 2 deletions src/node/helper/file-watcher.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import createDebug from 'debug'
import path from 'node:path'
import colors from 'picocolors'
import Watcher from 'watcher'
import { globalConfig } from '../global-config'
import { build } from './build'
import { _isPublicTypescript, type HmrFile } from './utils'
import { type HmrFile } from './server'
import { _isPublicTypescript, pkgName } from './utils'

const debug = createDebug('vite-plugin-public-typescript:file-watcher ===> ')

Expand Down Expand Up @@ -59,6 +61,6 @@ export function initWatcher(cb: (file: HmrFile) => void) {
handleFileChange(filePath, () => cb({ path: filePath, event: 'changed' }))
})
} catch (error) {
console.error(error)
console.error(colors.red(`[${pkgName}] `), error)
}
}
74 changes: 74 additions & 0 deletions src/node/helper/io.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import createDebug from 'debug'
import fs from 'fs-extra'
import path from 'node:path'
import { globalConfig } from '../global-config'
import { extractHashFromFileName, linebreak } from './utils'

const debug = createDebug('vite-plugin-public-typescript:io ===> ')

export function detectLastLine(string: string) {
const last = string.at(-1) || ''

return /(?:\r?\n)/g.test(last)
}

const newline = /\r\n|\r|\n/g
export function setEol(text: string) {
if (!detectLastLine(text)) {
text += linebreak
}

return text.replaceAll(newline, linebreak)
}

export function readJsonFile(file: string): Record<string, string> {
if (!fs.existsSync(file)) {
return {}
}

const cacheJson = fs.readFileSync(file, 'utf-8')
if (cacheJson) {
return JSON.parse(cacheJson)
}

return {}
}

export function writeFile(filename: string, content: string, hash = true): void {
const dir = path.dirname(filename)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}

const newContent = setEol(content)

if (fs.existsSync(filename)) {
if (hash) {
const _hash = globalConfig.get().hash
if (extractHashFromFileName(filename, _hash)) {
// if filename has hash, skip write file
debug('skip writeFile, filename has hash')
return
}
}

// Read content first
// if content is same, skip write file
const oldContent = fs.readFileSync(filename, 'utf-8')
debug('oldContent:', oldContent, 'newContent:', newContent)
if (oldContent && newContent === oldContent) {
debug('skip writeFile, content is same with old content:', oldContent)
return
}
}

fs.writeFileSync(filename, newContent)

debug('writeFile success:', filename)
}

export function writeJsonFile(filename: string, content: Record<string, string>) {
const formattedContent = JSON.stringify(content || {}, null, 2)
writeFile(filename, formattedContent, false)
return true
}
Loading

0 comments on commit 743e58f

Please sign in to comment.