Skip to content

Commit

Permalink
chore: update
Browse files Browse the repository at this point in the history
  • Loading branch information
qmhc committed Mar 13, 2024
1 parent 16251b7 commit 3002d2c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 28 deletions.
43 changes: 17 additions & 26 deletions src/plugin.ts
Expand Up @@ -29,7 +29,7 @@ import {
setModuleResolution,
toCapitalCase,
tryGetPkgPath,
wrapPromise
unwrapPromise
} from './utils'

import type { Alias, Logger } from 'vite'
Expand All @@ -45,7 +45,8 @@ const ctjsRE = /\.c(t|j)sx?$/
const fullRelativeRE = /^\.\.?\//
const defaultIndex = 'index.d.ts'

const logPrefix = cyan('[vite:dts]')
const pluginName = 'vite:dts'
const logPrefix = cyan(`[${pluginName}]`)
const bundleDebug = debug('vite-plugin-dts:bundle')

const fixedCompilerOptions: ts.CompilerOptions = {
Expand All @@ -62,6 +63,7 @@ const fixedCompilerOptions: ts.CompilerOptions = {

const noop = () => {}
const extPrefix = (file: string) => (mtjsRE.test(file) ? 'm' : ctjsRE.test(file) ? 'c' : '')
const tsToDts = (path: string) => `${path.replace(tsRE, '')}.d.ts`

const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g
const asteriskRE = /[*]+/g
Expand Down Expand Up @@ -127,7 +129,7 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
}

return {
name: 'vite:dts',
name: pluginName,

apply: 'build',

Expand Down Expand Up @@ -370,7 +372,7 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
}

if (typeof afterDiagnostic === 'function') {
await wrapPromise(afterDiagnostic(diagnostics))
await unwrapPromise(afterDiagnostic(diagnostics))
}

rootNames.forEach(file => {
Expand Down Expand Up @@ -479,7 +481,7 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {

const writeOutput = async (path: string, content: string, outDir: string, record = true) => {
if (typeof beforeWriteFile === 'function') {
const result = await wrapPromise(beforeWriteFile(path, content))
const result = await unwrapPromise(beforeWriteFile(path, content))

if (result === false) return

Expand Down Expand Up @@ -540,10 +542,6 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
const baseDir = dirname(filePath)

if (!isMapFile && content) {
// content = transformAliasImport(filePath, content, aliases, aliasesExclude)
// content = clearPureImport ? removePureImport(content) : content
// content = staticImport || rollupTypes ? transformDynamicImport(content) : content

content = transformCode({
filePath,
content,
Expand Down Expand Up @@ -613,34 +611,26 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
}

for (const name of entryNames) {
const path = multiple
? cleanPath(resolve(outDir, `${name.replace(tsRE, '')}.d.ts`))
: typesPath
const entryDtsPath = multiple ? cleanPath(resolve(outDir, tsToDts(name))) : typesPath

if (existsSync(path)) continue
if (existsSync(entryDtsPath)) continue

const index = normalizePath(
cleanPath(
resolve(outDir, relative(entryRoot, `${entries[name].replace(tsRE, '')}.d.ts`))
)
const sourceEntry = normalizePath(
cleanPath(resolve(outDir, relative(entryRoot, tsToDts(entries[name]))))
)

let fromPath = normalizePath(relative(dirname(path), index))
let fromPath = normalizePath(relative(dirname(entryDtsPath), sourceEntry))

fromPath = fromPath.replace(dtsRE, '')
fromPath = fullRelativeRE.test(fromPath) ? fromPath : `./${fromPath}`

let content = `export * from '${fromPath}'\n`

// if (existsSync(index) && hasExportDefault(await readFile(index, 'utf-8'))) {
// content += `import ${libName} from '${fromPath}'\nexport default ${libName}\n`
// }

if (emittedFiles.has(index) && hasExportDefault(emittedFiles.get(index)!)) {
if (emittedFiles.has(sourceEntry) && hasExportDefault(emittedFiles.get(sourceEntry)!)) {
content += `import ${libName} from '${fromPath}'\nexport default ${libName}\n`
}

await writeOutput(cleanPath(path), content, outDir)
await writeOutput(cleanPath(entryDtsPath), content, outDir)
}

bundleDebug('insert index')
Expand All @@ -667,7 +657,7 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {

if (multiple) {
for (const name of entryNames) {
const path = cleanPath(resolve(outDir, `${name.replace(tsRE, '')}.d.ts`))
const path = cleanPath(resolve(outDir, tsToDts(name)))

rollupDeclarationFiles({
root,
Expand Down Expand Up @@ -737,14 +727,15 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
}

if (typeof afterBuild === 'function') {
await wrapPromise(afterBuild(emittedFiles))
await unwrapPromise(afterBuild(emittedFiles))
}

bundleDebug('finish')
logger.info(
green(`${logPrefix} Declaration files built in ${timeRecord + Date.now() - startTime}ms.\n`)
)
},

generateBundle(_, bundle) {
if (declarationOnly) {
for (const id of Object.keys(bundle)) {
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Expand Up @@ -45,7 +45,7 @@ export function isPromise(value: unknown): value is Promise<any> {
)
}

export async function wrapPromise<T>(maybePromise: T | Promise<T>) {
export async function unwrapPromise<T>(maybePromise: T | Promise<T>) {
return isPromise(maybePromise) ? await maybePromise : maybePromise
}

Expand Down
9 changes: 8 additions & 1 deletion tests/utils.spec.ts
Expand Up @@ -14,7 +14,8 @@ import {
mergeObjects,
normalizePath,
queryPublicPath,
toCapitalCase
toCapitalCase,
unwrapPromise
} from '../src/utils'

describe('utils tests', () => {
Expand Down Expand Up @@ -56,6 +57,12 @@ describe('utils tests', () => {
expect(isPromise({ then: () => {}, catch: () => {} })).toBe(true)
})

it('test: unwrapPromise', async () => {
expect(await unwrapPromise(false)).toBe(false)
expect(await unwrapPromise('')).toBe('')
expect(await unwrapPromise(Promise.resolve().then(() => 1))).toBe(1)
})

it('test: mergeObjects', () => {
expect(mergeObjects({ a: '1' }, { b: '3' })).toEqual({ a: '1', b: '3' })
expect(mergeObjects({ a: '1', b: '2' }, { b: '3' })).toEqual({ a: '1', b: '3' })
Expand Down

0 comments on commit 3002d2c

Please sign in to comment.