Skip to content

Commit

Permalink
feat: support memory destination
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed Sep 13, 2023
1 parent 62d6fd4 commit b5c2c23
Show file tree
Hide file tree
Showing 33 changed files with 238 additions and 174 deletions.
22 changes: 15 additions & 7 deletions __test__/basic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,16 @@ vi.mock('fs-extra', async () => {

function initCache() {
const cache = new ManifestCache()
cache.setCache({ key: 'name', value: 'value' })
cache.setCache({ key: 'typescript', value: 'powerful' })
cache.set({
x: {
path: 'x.js',
_code: 'console.log("x")',
},
y: {
path: 'y.js',
_code: 'console.log("y")',
},
})
return cache
}

Expand Down Expand Up @@ -70,17 +78,17 @@ afterEach((ctx) => {

describe('manifestCache', () => {
test('should set cache and get cache right', ({ cache }) => {
expect(cache.getCache('name')).toBe('value')
expect(cache.getByKey('x')).toStrictEqual({ path: 'x.js', _code: 'console.log("x")' })
})

test('should remove cache', ({ cache }) => {
cache.removeCache('name')
cache.remove('x')

expect(cache.getCache('name')).toBeFalsy()
expect(cache.getByKey('x')).toBeFalsy()
})

test('should get all', ({ cache }) => {
const v = cache.getAll()
const v = cache.get()
expect(Object.keys(v).length === 2).toBe(true)
})

Expand All @@ -102,7 +110,7 @@ describe('manifestCache', () => {
{
const content = fs.readFileSync(manifestPath, 'utf-8')
const c = initCache()
expect(eq(JSON.parse(content), c.getAll())).toBe(true)
expect(eq(JSON.parse(content), c.extractPath(c.get()))).toBe(true)
}
})
})
27 changes: 4 additions & 23 deletions __test__/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
setEol,
validateOptions,
} from '../src/helper/utils'
import { getGlobalConfig, setGlobalConfig } from '../src/helper/GlobalConfigBuilder'
import { globalConfigBuilder } from '../src/helper/GlobalConfigBuilder'

describe('vite-plugin-public-typescript', () => {
it('should return true when filePath is a public typescript file', () => {
Expand Down Expand Up @@ -70,14 +70,8 @@ describe('vite-plugin-public-typescript', () => {
expect(a).toBe(b)
})

test('should getGlobalConfig throw error', () => {
expect(() => getGlobalConfig()).toThrowError('init')
})

test('should get globalConfig', () => {
// @ts-expect-error
setGlobalConfig({ config: { publicDir: 'public' }, inputDir: 'publicTypescript' })
expect(() => getGlobalConfig()).not.toThrowError()
expect(() => globalConfigBuilder.get()).not.toThrowError()
})

test('should extract hash', () => {
Expand All @@ -96,22 +90,9 @@ describe('vite-plugin-public-typescript', () => {
ssrBuild: false,
esbuildOptions: {},
sideEffects: false,
}
destination: 'file',
} as const

expect(() => validateOptions(opts)).not.toThrowError()
})

test('should validate options throw error', () => {
const opts = {
inputDir: '/publicTypescript/foo',
outputDir: 'js',
manifestName: 'manifest',
hash: true,
ssrBuild: false,
esbuildOptions: {},
sideEffects: false,
}

expect(() => validateOptions(opts)).toThrowError('dir')
})
})
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"esbuild": "^0.17.12",
"fs-extra": "^11.1.1",
"on-change": "^4.0.2",
"sirv": "^2.0.3",
"tiny-glob": "^0.2.9",
"watcher": "^2.2.2"
},
Expand Down
1 change: 1 addition & 0 deletions playground/spa/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<body>
<div id="root"></div>

</script>
<script type="module" src="/src/main.tsx"></script>


Expand Down
2 changes: 1 addition & 1 deletion playground/spa/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"private": true,
"scripts": {
"dev": "vite",
"debug": "cross-env DEBUG='*===>*' vite",
"debug": "cross-env DEBUG='MemoryCacheProcessor*,index*,ManifestCache*' vite",
"build": "vite build",
"preview": "vite preview"
},
Expand Down
File renamed without changes.
File renamed without changes.
5 changes: 5 additions & 0 deletions playground/spa/public-typescript/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"haha": "/js/haha.bdaaba63.js",
"index": "/js/index.cccf1b56.js",
"test": "/js/test.40879d01.js"
}
1 change: 1 addition & 0 deletions playground/spa/public-typescript/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('this is a')
1 change: 0 additions & 1 deletion playground/spa/publicTypescript/manifest.json

This file was deleted.

1 change: 0 additions & 1 deletion playground/spa/publicTypescript/test.ts

This file was deleted.

2 changes: 1 addition & 1 deletion playground/spa/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState } from 'react'
import manifest from '../publicTypescript/manifest.json'
import manifest from '../public-typescript/manifest.json'
import reactLogo from './assets/react.svg'
import './App.css'

Expand Down
1 change: 1 addition & 0 deletions playground/spa/temp/1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('temp')
2 changes: 1 addition & 1 deletion playground/spa/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"baseUrl": ".",
"types": ["vite/client"]
},
"include": ["src", "publicTypescript"],
"include": ["src", "public-typescript"],
"references": [{ "path": "./tsconfig.node.json" }],
"exclude": ["**/*.js"]
}
2 changes: 1 addition & 1 deletion playground/spa/tsconfig.node.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"resolveJsonModule": true,
"baseUrl": "."
},
"include": ["vite.config.ts", "./publicTypescript/manifest.json"]
"include": ["vite.config.ts", "public-typescript/manifest.json"]
}
28 changes: 10 additions & 18 deletions playground/spa/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,37 @@
import path from 'path'
import type { HtmlTagDescriptor } from 'vite'
import { defineConfig } from 'vite'
import { publicTypescript } from 'vite-plugin-public-typescript'
import react from '@vitejs/plugin-react'
import glob from 'tiny-glob'
import manifest from './publicTypescript/manifest.json'
import manifest from './public-typescript/manifest.json'

// https://vitejs.dev/config/
export default defineConfig({
build: {
rollupOptions: {
external: ['virtual:my-module'],
},
},
define: {
haha: JSON.stringify('custom define!'),
app: JSON.stringify({ hello: 'world' }),
},
plugins: [
react(),
publicTypescript({
inputDir: 'publicTypescript',
inputDir: 'public-typescript',
manifestName: 'manifest',
hash: true,
outputDir: '/',
buildDestination: 'memory',
outputDir: '/js',
destination: 'memory',
}),

{
name: 'add-script',
async transformIndexHtml(html) {
const scripts = await glob('./public/*.js')
const tags: HtmlTagDescriptor[] = scripts.map((s) => {
return {
const tags: HtmlTagDescriptor[] = [
{
tag: 'script',
attrs: {
src: manifest[path.parse(s).name.split('.')[0]],
src: manifest.test,
},
injectTo: 'head-prepend',
}
})
injectTo: 'body',
},
]

return {
html,
Expand Down
3 changes: 3 additions & 0 deletions playground/ssr/public-typescript/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"ssr": "/ssr.2507f2a9.js"
}
File renamed without changes.
1 change: 0 additions & 1 deletion playground/ssr/public/ssr.4c5dba79.js

This file was deleted.

3 changes: 0 additions & 3 deletions playground/ssr/publicTypescript/custom-manifest.json

This file was deleted.

2 changes: 1 addition & 1 deletion playground/ssr/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'fs/promises'
import express from 'express'
import manifest from './publicTypescript/custom-manifest.json' assert { type: 'json' }
import manifest from './public-typescript/manifest.json' assert { type: 'json' }

// Constants
const isProduction = process.env.NODE_ENV === 'production'
Expand Down
2 changes: 1 addition & 1 deletion playground/ssr/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { publicTypescript } from 'vite-plugin-public-typescript'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [publicTypescript()],
plugins: [publicTypescript({ destination: 'memory' })],
})
18 changes: 15 additions & 3 deletions pnpm-lock.yaml

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

27 changes: 27 additions & 0 deletions src/helper/AbsCacheProcessor.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { normalizePath } from 'vite'
import type { TGlobalConfig } from './GlobalConfigBuilder'

export interface IDeleteFile {
fileName: string
jsFileName?: string
Expand All @@ -13,4 +16,28 @@ export interface IAddFile {
export abstract class AbsCacheProcessor {
abstract deleteOldJs(args: IDeleteFile): Promise<void>
abstract addNewJs(args: IAddFile): Promise<void>
setCache(args: IAddFile, globalConfig: TGlobalConfig) {
const { contentHash, code = '', fileName } = args
const { cache, outputDir } = globalConfig

function getOutputPath(p: string, hash?: string) {
hash = hash ? `.${hash}` : ''
return normalizePath(`${p}/${fileName}${hash}.js`)
}

let outPath = getOutputPath(outputDir)
if (contentHash) {
outPath = getOutputPath(outputDir, contentHash)
}

cache.set({
[fileName]: {
path: outPath,
_code: code,
_hash: contentHash,
},
})

return outPath
}
}
Loading

0 comments on commit b5c2c23

Please sign in to comment.