Skip to content

Commit

Permalink
feat: path-like option support relative/absolute
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed May 31, 2024
1 parent 0338223 commit 24a2607
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 56 deletions.
2 changes: 1 addition & 1 deletion README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pnpm add vite-plugin-public-typescript -D
| -------------- | -------------------------------------- | --------------------------------------------- | ---------------------------------------------- |
| inputDir | `string` | `public-typescript` | 存放需要编译的 `typescript` 的目录 |
| publicDir | `string` | vite config 中的 publicDir | public 目录 |
| outputDir | `string` | `/` | 输出公共 javascript 的目录,相对于 `publicDir` |
| outputDir | `string` | '' | 输出公共 javascript 的目录,相对于 `publicDir` |
| esbuildOptions | `BuildOptions` | `{}` | esbuild 构建选项 |
| babel | `boolean | ESBuildPluginBabelOptions` | `false` | babel编译(如果需要兼容es6以下浏览器,请开启) |
| manifestName | `string` | `manifest` | `manifest` 的文件名 |
Expand Down
2 changes: 1 addition & 1 deletion playground/spa/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default defineConfig(() => ({
plugins: [
react(),
publicTypescript({
outputDir: 'out',
outputDir: '/out',
destination: 'memory',
babel: true,
}),
Expand Down
9 changes: 3 additions & 6 deletions src/node/global-config/GlobalConfigBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,13 @@ import { type OptionsTypeWithDefault } from '../helper/utils'
import { type CacheValue, type ManifestCache } from '../manifest-cache/ManifestCache'
import { type BaseCacheProcessor } from '../processor/BaseCacheProcessor'

export type UserConfig<T extends CacheValue = CacheValue> = {
export type GlobalConfig<T extends CacheValue = CacheValue> = Required<OptionsTypeWithDefault> & {
viteDevServer?: ViteDevServer
manifestCache: ManifestCache<T>
originFilesGlob: string[]
viteConfig: ResolvedConfig
cacheProcessor: BaseCacheProcessor<T>
logger: Logger
} & Required<OptionsTypeWithDefault>

export type GlobalConfig<T extends CacheValue = CacheValue> = UserConfig<T> & {
viteDevServer?: ViteDevServer
}

export class GlobalConfigBuilder<T extends CacheValue = CacheValue> {
Expand All @@ -22,7 +19,7 @@ export class GlobalConfigBuilder<T extends CacheValue = CacheValue> {
this._globalConfig = {} as GlobalConfig<T>
}

init(c: UserConfig<T>) {
init(c: GlobalConfig<T>) {
this._globalConfig = {
...c,
}
Expand Down
5 changes: 3 additions & 2 deletions src/node/helper/default-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ export function resolveOptions(
resolvedViteConfig?: ResolvedConfig,
options?: VitePublicTypescriptOptions,
): OptionsTypeWithDefault {
const publicDir = resolve(resolvedViteConfig?.root, resolvedViteConfig?.publicDir || 'public')
const publicDir = options?.publicDir
? resolve(resolvedViteConfig?.root, options?.publicDir)
: resolvedViteConfig?.publicDir || resolve(resolvedViteConfig?.root, 'public')

return {
inputDir: resolve(resolvedViteConfig?.root, options?.inputDir || 'public-typescript'),
// 相对于 publicDir
// 用户也可以自定义输出目录, e.g. outputDir: 'out/js'
outputDir: resolve(publicDir, options?.outputDir || ''),
esbuildOptions: options?.esbuildOptions ?? {},
babel: options?.babel ?? false,
Expand Down
29 changes: 8 additions & 21 deletions src/node/helper/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,16 @@ export function isInTest() {
return process.env.VITEST || isCI
}

export function isPublicTypescript(args: { filePath: string; inputDir: string; root: string }) {
const { filePath, root, inputDir } = args
export function isPublicTypescript(args: { filePath: string; inputDir: string }) {
const { filePath, inputDir } = args

return (
path.extname(filePath) === '.ts' &&
normalizePath(path.resolve(root, inputDir)).endsWith(normalizePath(path.dirname(filePath)))
)
return path.extname(filePath) === '.ts' && normalizePath(inputDir).endsWith(normalizePath(path.dirname(filePath)))
}

export function _isPublicTypescript(filePath: string) {
return isPublicTypescript({
filePath,
inputDir: globalConfig.get('inputDir'),
root: globalConfig.get('viteConfig')!.root,
})
}

Expand Down Expand Up @@ -117,14 +113,13 @@ export function normalizeAssetsDirPath(dir: string) {
}

export function getInputDir(resolvedRoot: string, originInputDir: string, suffix = '') {
return normalizePath(path.resolve(resolvedRoot, `${originInputDir}${suffix}`))
return normalizePath(path.join(resolvedRoot, `${originInputDir}${suffix}`))
}

export async function findAllOldJsFile(args: { originFiles: string[]; outputDir: string }) {
const { outputDir, originFiles } = args
const dir = outputDir
const oldFiles: string[] = []
if (fs.existsSync(dir)) {
if (fs.existsSync(outputDir)) {
for (const originFile of originFiles) {
const old = await glob(normalizePath(`${outputDir}/${originFile}.?(*.)js`))
if (old.length > 0) {
Expand All @@ -145,20 +140,12 @@ export function removeOldJsFiles(oldFiles: string[]) {
}
}

// NOTE: remmember call this before write compiled js file to disk
export function removeBase(filePath: string, base: string): string {
const devBase = base.at(-1) === '/' ? base : `${base}/`
return filePath.startsWith(devBase) ? filePath.slice(devBase.length - 1) : filePath
}

export async function setupGlobalConfig(viteConfig: ResolvedConfig, opts: OptionsTypeWithDefault) {
const resolvedRoot = normalizePath(viteConfig.root ? path.resolve(viteConfig.root) : process.cwd())

fs.ensureDirSync(getInputDir(resolvedRoot, opts.inputDir))
fs.ensureDirSync(opts.inputDir)

const originFilesGlob = await glob(getInputDir(resolvedRoot, opts.inputDir, `/*.ts`), {
const originFilesGlob = await glob('*.ts', {
absolute: true,
cwd: resolvedRoot,
cwd: opts.inputDir,
})

const cacheProcessor = initCacheProcessor(opts, manifestCache)
Expand Down
14 changes: 8 additions & 6 deletions src/node/processor/FileCacheProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ export class FileCacheProcessor extends ManifestCacheProcessor {
async deleteOldJs(args: DeleteFileArgs): Promise<void> {
const { originFile, compiledFileName = '', silent } = args

const { outputDir } = globalConfig.get(['outputDir', 'viteConfig'])
const { outputDir } = globalConfig.get(['outputDir'])

let oldFiles: string[] = []
fs.ensureDirSync(outputDir)
try {
fs.ensureDirSync(outputDir)
oldFiles = await findAllOldJsFile({
originFiles: [originFile],
outputDir,
Expand Down Expand Up @@ -62,12 +62,14 @@ export class FileCacheProcessor extends ManifestCacheProcessor {

async addNewJs(args: AddFileArgs): Promise<void> {
const { code = '' } = args
const { publicDir } = globalConfig.get('viteConfig')

const jsFilePath = this.setCache(args, globalConfig.all)
const pathToDisk = this.setCache(args, globalConfig.all)
const jsFilePath = normalizePath(path.join(publicDir, pathToDisk))

if (!fs.existsSync(jsFilePath)) {
fs.ensureFileSync(normalizePath(jsFilePath))
}
if (!jsFilePath) return

fs.ensureDirSync(path.dirname(jsFilePath))

writeFile(jsFilePath, code)
}
Expand Down
39 changes: 20 additions & 19 deletions src/node/processor/ManifestCacheProcessor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import createDebug from 'debug'
import path from 'node:path'
import { normalizePath } from 'vite'
import { type GlobalConfig } from '../global-config/GlobalConfigBuilder'
import { type CacheValueEx } from '../manifest-cache'
Expand All @@ -24,6 +23,11 @@ export interface AddFileArgs {
code?: string
}

function removeBase(filePath: string, base: string): string {
const devBase = base.at(-1) === '/' ? base : `${base}/`
return filePath.startsWith(devBase) ? filePath.slice(devBase.length - 1) : filePath
}

export abstract class ManifestCacheProcessor extends BaseCacheProcessor<CacheValueEx> {
constructor(manifestCache: ManifestCache<CacheValueEx>) {
super(manifestCache)
Expand All @@ -41,30 +45,27 @@ export abstract class ManifestCacheProcessor extends BaseCacheProcessor<CacheVal
const { contentHash, originFile, code } = args
const { outputDir, base, publicDir } = config

// 用户输入的outputDir
const outputDirRelativePublicDir = normalizePath(outputDir.slice(publicDir.length))

const pathWithBase = this.genCacheItemPath({
base,
contentHash,
originFile,
outputDir: outputDirRelativePublicDir,
})

this.manifestCache.set({
[originFile]: {
path: this.genCacheItemPath({
base,
contentHash,
originFile,
outputDir: path.relative(publicDir, outputDir),
}),
path: pathWithBase,
_code: code || '',
_hash: contentHash,
_pathToDisk: this.genCacheItemPath({
contentHash,
originFile,
outputDir: path.relative(publicDir, outputDir),
}),
_pathToDisk: removeBase(pathWithBase, base),
},
})

const absFilePath = this.genCacheItemPath({
contentHash,
originFile,
outputDir,
})
debug('setCache absFilePath:', absFilePath)
return absFilePath
const pathToDisk = this.manifestCache.get(originFile)._pathToDisk
debug('setCache absFilePath:', pathToDisk)
return pathToDisk!
}
}

0 comments on commit 24a2607

Please sign in to comment.