Skip to content

Commit

Permalink
fix: support export type rewrites
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Nov 15, 2022
1 parent 0bc6c83 commit 3a369fb
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions packages/vite/scripts/emitCjsTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@ async function main() {
let text = fs.readFileSync(file, 'utf8')

const [imports] = lexer.parse(text)
for (const i of [...imports].reverse()) {
const typeImports = parseTypeImports(text, true)
const allImports = [...imports, ...typeImports]
// In reverse order
.sort((a, b) => b.s - a.s)

for (const i of allImports) {
let id = i.n
if (!id || !/^\.\.?(?:\/|$)/.test(id)) {
if (!id || !/^\.\.?(?:\/|$)/.test(id) || id.endsWith('.cjs')) {
continue
}

Expand Down Expand Up @@ -45,4 +50,44 @@ function isDirectory(file: string) {
}
}

// This assumes no each import/export statement is on its own line.
function parseTypeImports(code: string, exportsOnly?: boolean) {
const imports = []

const openKeywords = exportsOnly ? ['export'] : ['import', 'export']
const openPattern = [['', '\n'], openKeywords, ['type']]
const fromPattern = [['from'], ['"', "'"]]

let cursor = 0
let pattern = openPattern
let patternIndex = 0

const words = code.split(/([\w/\-@.]+|\n)/g)
for (let i = 0; i < words.length; i++) {
const word = words[i].replace(/ /g, '')
if (pattern[patternIndex].includes(word)) {
if (++patternIndex === pattern.length) {
patternIndex = 0
if (pattern === openPattern) {
pattern = fromPattern
} else if (pattern === fromPattern) {
pattern = openPattern
const moduleSpecifier = words[i + 1]
const start = cursor + words[i].length
imports.push({
s: start,
e: start + moduleSpecifier.length,
n: moduleSpecifier
})
}
}
} else if (patternIndex > 0 && word) {
patternIndex = 0
}
cursor += words[i].length
}

return imports
}

main()

0 comments on commit 3a369fb

Please sign in to comment.