Skip to content

Commit

Permalink
feat: support multiple entries for lib mode
Browse files Browse the repository at this point in the history
fix #136
  • Loading branch information
qmhc committed Oct 30, 2022
1 parent 01cc125 commit 1fafe54
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 38 deletions.
2 changes: 1 addition & 1 deletion example/package.json
Expand Up @@ -12,7 +12,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^3.2.0",
"@vitejs/plugin-vue-jsx": "^2.1.0",
"vite": "^3.2.0",
"vite": "^3.2.1",
"vite-plugin-dts": "workspace:*"
}
}
9 changes: 9 additions & 0 deletions example/src/main.ts
@@ -0,0 +1,9 @@
export { addOne, add } from '@/components/js-test.js'

export { default as App } from './App.vue'
export { default as Setup } from '@/components/Setup.vue'
export { test } from '@/components/test'

export type { User } from './types'
export type { DtsType } from './dts-types'
export type { Component } from '@/components'
9 changes: 5 additions & 4 deletions example/vite.config.ts
Expand Up @@ -6,6 +6,7 @@ import vueJsx from '@vitejs/plugin-vue-jsx'
import { dtsPlugin } from '../src/plugin'
// import dtsPlugin from 'vite-plugin-dts'

emptyDir(resolve(__dirname, 'dist'))
emptyDir(resolve(__dirname, 'types'))

export default defineConfig({
Expand All @@ -18,10 +19,10 @@ export default defineConfig({
},
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
entry: [resolve(__dirname, 'src/index.ts'), resolve(__dirname, 'src/main.ts')],
name: 'Test',
formats: ['es'],
fileName: 'test'
formats: ['es']
// fileName: 'test'
},
rollupOptions: {
external: ['vue']
Expand All @@ -36,7 +37,7 @@ export default defineConfig({
staticImport: true,
skipDiagnostics: false,
logDiagnostics: true,
// rollupTypes: true,
rollupTypes: true,
insertTypesEntry: true
}),
vue(),
Expand Down
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -49,7 +49,7 @@
"tsx": "^3.11.0",
"typescript": "4.8.4",
"unbuild": "^0.9.4",
"vite": "^3.2.0",
"vite": "^3.2.1",
"vitest": "^0.24.3",
"vue": "3.2.41"
},
Expand Down
107 changes: 75 additions & 32 deletions src/plugin.ts
Expand Up @@ -100,7 +100,7 @@ export function dtsPlugin(options: PluginOptions = {}): Plugin {
let libName: string
let indexName: string
let aliases: Alias[]
let entries: string[]
let entries: Record<string, string>
let logger: Logger
let project: Project
let tsConfigPath: string
Expand Down Expand Up @@ -166,9 +166,13 @@ export function dtsPlugin(options: PluginOptions = {}): Plugin {
indexName = defaultIndex
} else {
const filename = config.build.lib.fileName ?? defaultIndex
const entry =
typeof config.build.lib.entry === 'string'
? config.build.lib.entry
: Object.values(config.build.lib.entry)[0]

libName = config.build.lib.name || '_default'
indexName = typeof filename === 'string' ? filename : filename('es')
indexName = typeof filename === 'string' ? filename : filename('es', entry)

if (!dtsRE.test(indexName)) {
indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, '') : indexName}.d.ts`
Expand Down Expand Up @@ -218,10 +222,14 @@ export function dtsPlugin(options: PluginOptions = {}): Plugin {
},

buildStart(inputOptions) {
if (!isBundle && (insertTypesEntry || rollupTypes)) {
entries = Array.isArray(inputOptions.input)
? inputOptions.input
: Object.values(inputOptions.input)
if (Array.isArray(inputOptions.input)) {
entries = inputOptions.input.reduce((prev, current) => {
prev[basename(current)] = current

return prev
}, {} as Record<string, string>)
} else {
entries = { ...inputOptions.input }
}
},

Expand Down Expand Up @@ -433,43 +441,51 @@ export function dtsPlugin(options: PluginOptions = {}): Plugin {
if (insertTypesEntry || rollupTypes) {
const pkgPath = resolve(root, 'package.json')
const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, 'utf-8')) : {}
const entryNames = Object.keys(entries)
const types = pkg.types || pkg.typings
const multiple = entryNames.length > 1

const typesPath = types ? resolve(root, types) : resolve(outputDir, indexName)

let typesPath = types ? resolve(root, types) : resolve(outputDir, indexName)
for (const name of entryNames) {
let filePath = multiple ? resolve(outputDir, name.replace(tsRE, '.d.ts')) : typesPath

if (!fs.existsSync(typesPath)) {
const entry = entries[0]
const outputIndex = resolve(outputDir, relative(entryRoot, entry.replace(tsRE, '.d.ts')))
if (fs.existsSync(filePath)) continue

let filePath = normalizePath(relative(dirname(typesPath), outputIndex))
const index = resolve(
outputDir,
relative(entryRoot, entries[name].replace(tsRE, '.d.ts'))
)

filePath = filePath.replace(dtsRE, '')
filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`
let fromPath = normalizePath(relative(dirname(filePath), index))

let content = `export * from '${filePath}'\n`
fromPath = fromPath.replace(dtsRE, '')
fromPath = fullRelativeRE.test(fromPath) ? fromPath : `./${fromPath}`

if (fs.existsSync(outputIndex)) {
const entryCodes = await fs.readFile(outputIndex, 'utf-8')
let content = `export * from '${fromPath}'\n`

if (fs.existsSync(index)) {
const entryCodes = await fs.readFile(index, 'utf-8')

if (entryCodes.includes('export default')) {
content += `import ${libName} from '${filePath}'\nexport default ${libName}\n`
content += `import ${libName} from '${fromPath}'\nexport default ${libName}\n`
}
}

let result: ReturnType<typeof beforeWriteFile>

if (typeof beforeWriteFile === 'function') {
result = beforeWriteFile(typesPath, content)
result = beforeWriteFile(filePath, content)

if (result && isNativeObj(result)) {
typesPath = result.filePath ?? typesPath
filePath = result.filePath ?? filePath
content = result.content ?? content
}
}

if (result !== false) {
await fs.writeFile(typesPath, content, 'utf-8')
wroteFiles.add(normalizePath(typesPath))
await fs.writeFile(filePath, content, 'utf-8')
wroteFiles.add(normalizePath(filePath))
}
}

Expand All @@ -478,22 +494,49 @@ export function dtsPlugin(options: PluginOptions = {}): Plugin {
if (rollupTypes) {
logger.info(green(`${logPrefix} Start rollup declaration files...`))

rollupDeclarationFiles({
root,
tsConfigPath,
compilerOptions,
outputDir,
entryPath: typesPath,
fileName: basename(typesPath)
})
const rollupFiles = new Set<string>()

if (multiple) {
for (const name of entryNames) {
const path = resolve(outputDir, name.replace(tsRE, '.d.ts'))

rollupDeclarationFiles({
root,
tsConfigPath,
compilerOptions,
outputDir,
entryPath: path,
fileName: basename(path)
})

const wroteFile = normalizePath(typesPath)
const wroteFile = normalizePath(path)

wroteFiles.delete(wroteFile)
rollupFiles.add(wroteFile)
}
} else {
rollupDeclarationFiles({
root,
tsConfigPath,
compilerOptions,
outputDir,
entryPath: typesPath,
fileName: basename(typesPath)
})

const wroteFile = normalizePath(typesPath)

wroteFiles.delete(wroteFile)
rollupFiles.add(wroteFile)
}

wroteFiles.delete(wroteFile)
await runParallel(os.cpus().length, Array.from(wroteFiles), f => fs.unlink(f))
removeDirIfEmpty(outputDir)
wroteFiles.clear()
wroteFiles.add(wroteFile)

for (const file of rollupFiles) {
wroteFiles.add(file)
}

if (copyDtsFiles) {
await runParallel(os.cpus().length, dtsOutputFiles, async ({ path, content }) => {
Expand Down

0 comments on commit 1fafe54

Please sign in to comment.