Skip to content

Commit

Permalink
fix: sync diff line to mappings after transform
Browse files Browse the repository at this point in the history
fix #356
  • Loading branch information
qmhc committed Aug 5, 2024
1 parent e873107 commit cd5ba32
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 24 deletions.
3 changes: 3 additions & 0 deletions examples/ts/src/dynamic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface DynamicImportType {
a: number
}
3 changes: 3 additions & 0 deletions examples/ts/src/dynamic2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface DynamicImportType2 {
a: number
}
3 changes: 3 additions & 0 deletions examples/ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import data from './data.json'

import type { TestBase } from '@/test'

export const dy: import('./dynamic').DynamicImportType = { a: 1 }
export const dy1: import('./dynamic2').DynamicImportType2 = { a: 1 }

export interface Test extends TestBase {
count: number
}
Expand Down
7 changes: 5 additions & 2 deletions examples/ts/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ export default defineConfig({
// aliasesExclude: [/^@components/],
staticImport: true,
// insertTypesEntry: true,
rollupTypes: true,
declarationOnly: true
rollupTypes: false,
declarationOnly: true,
compilerOptions: {
declarationMap: true
}
})
]
})
Expand Down
2 changes: 1 addition & 1 deletion examples/vue/components/BothScripts.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ defineExpose({ inc })
export interface BothScriptsProps {
/** comment */
tag: string
tag: string,
count: number
}
Expand Down
2 changes: 1 addition & 1 deletion examples/vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"private": true,
"scripts": {
"build": "DEBUG=\"vite-plugin-dts:bundle\" vite build",
"tsc": "vue-tsc --declaration --emitDeclarationOnly --outDir tsc-dist"
"tsc": "vue-tsc --declaration --emitDeclarationOnly --declarationMap --outDir tsc-dist"
},
"dependencies": {
"vue": "^3.4.32"
Expand Down
67 changes: 50 additions & 17 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,15 +543,31 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
bundleDebug('emit output patch')

const currentDir = host.getCurrentDirectory()
const declarationFiles = new Map<string, string>()
const mapFiles = new Map<string, string>()
const prependMappings = new Map<string, string>()

for (const [filePath, content] of outputFiles.entries()) {
if (filePath.endsWith('.map')) {
mapFiles.set(filePath, content)
} else {
declarationFiles.set(filePath, content)
}
}

await runParallel(
cpus().length,
Array.from(outputFiles.entries()),
Array.from(declarationFiles.entries()),
async ([filePath, content]) => {
const isMapFile = filePath.endsWith('.map')
const baseDir = dirname(filePath)
const newFilePath = resolve(
outDir,
relative(
entryRoot,
cleanVueFileName ? filePath.replace('.vue.d.ts', '.d.ts') : filePath
)
)

if (!isMapFile && content) {
if (content) {
const result = transformCode({
filePath,
content,
Expand All @@ -564,8 +580,22 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {

content = result.content
declareModules.push(...result.declareModules)

if (result.diffLineCount) {
prependMappings.set(`${newFilePath}.map`, ';'.repeat(result.diffLineCount))
}
}

await writeOutput(newFilePath, content, outDir)
}
)

await runParallel(
cpus().length,
Array.from(mapFiles.entries()),
async ([filePath, content]) => {
const baseDir = dirname(filePath)

filePath = resolve(
outDir,
relative(
Expand All @@ -574,22 +604,25 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
)
)

if (isMapFile) {
try {
const sourceMap: { sources: string[] } = JSON.parse(content)
try {
const sourceMap: { sources: string[], mappings: string } = JSON.parse(content)

sourceMap.sources = sourceMap.sources.map(source => {
return normalizePath(
relative(
dirname(filePath),
resolve(currentDir, relative(publicRoot, baseDir), source)
)
sourceMap.sources = sourceMap.sources.map(source => {
return normalizePath(
relative(
dirname(filePath),
resolve(currentDir, relative(publicRoot, baseDir), source)
)
})
content = JSON.stringify(sourceMap)
} catch (e) {
logger.warn(`${logPrefix} ${yellow('Processing source map fail:')} ${filePath}`)
)
})

if (prependMappings.has(filePath)) {
sourceMap.mappings = `${prependMappings.get(filePath)}${sourceMap.mappings}`
}

content = JSON.stringify(sourceMap)
} catch (e) {
logger.warn(`${logPrefix} ${yellow('Processing source map fail:')} ${filePath}`)
}

await writeOutput(filePath, content, outDir)
Expand Down
9 changes: 7 additions & 2 deletions src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,13 @@ export function transformCode(options: {
}

let indexCount = 0
let importCount = 0

walkSourceFile(ast, (node, parent) => {
if (ts.isImportDeclaration(node)) {
if (!node.importClause) {
options.clearPureImport && s.remove(node.pos, node.end)
++importCount
} else if (
ts.isStringLiteral(node.moduleSpecifier) &&
(node.importClause.name ||
Expand Down Expand Up @@ -137,6 +139,7 @@ export function transformCode(options: {
}

s.remove(node.pos, node.end)
++importCount
}

return false
Expand Down Expand Up @@ -234,11 +237,13 @@ export function transformCode(options: {
prependImports += `import { ${Array.from(importSet).join(', ')} } from '${libName}';\n`
})

s.prepend(prependImports)
s.trimStart('\n').prepend(prependImports)

return {
content: s.toString(),
declareModules
declareModules,
diffLineCount:
importMap.size && importCount < importMap.size ? importMap.size - importCount : null
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/transform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe('transform tests', () => {
expect(
transformCode(options('import { Type } from "./test";\nconst test: import("./test").Test;'))
.content
).toEqual("import { Type, Test } from './test';\n\nconst test: Test;")
).toEqual("import { Type, Test } from './test';\nconst test: Test;")

expect(
transformCode(options("const a: import('foo').A<{ b: import('foo').B<import('foo').C> }>"))
Expand Down

0 comments on commit cd5ba32

Please sign in to comment.