Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: emit .d.cts files #10945

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
"types": "./dist/node/index.d.ts",
"exports": {
".": {
"types": "./dist/node/index.d.ts",
"types": {
"import": "./dist/node/index.d.ts",
"require": "./dist/node-cjs/index.d.cts"
},
"import": "./dist/node/index.js",
"require": "./index.cjs"
},
Expand Down Expand Up @@ -46,12 +49,13 @@
"dev": "rimraf dist && pnpm run build-bundle -w",
"build": "rimraf dist && run-s build-bundle build-types",
"build-bundle": "rollup --config rollup.config.ts --configPlugin typescript",
"build-types": "run-s build-types-temp build-types-pre-patch build-types-roll build-types-post-patch build-types-check",
"build-types": "run-s build-types-temp build-types-pre-patch build-types-roll build-types-post-patch build-types-check build-emit-cjs-types",
"build-types-temp": "tsc --emitDeclarationOnly --outDir temp/node -p src/node",
"build-types-pre-patch": "tsx scripts/prePatchTypes.ts",
"build-types-roll": "api-extractor run && rimraf temp",
"build-types-post-patch": "tsx scripts/postPatchTypes.ts",
"build-types-check": "tsc --project tsconfig.check.json",
"build-emit-cjs-types": "tsx scripts/emitCjsTypes.ts",
"lint": "eslint --cache --ext .ts src/**",
"format": "prettier --write --cache --parser typescript \"src/**/*.ts\"",
"prepublishOnly": "npm run build"
Expand Down
21 changes: 20 additions & 1 deletion packages/vite/rollup.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { spawn } from 'node:child_process'
import nodeResolve from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import commonjs from '@rollup/plugin-commonjs'
Expand Down Expand Up @@ -179,7 +180,11 @@ function createCjsConfig(isProduction: boolean) {
...Object.keys(pkg.dependencies),
...(isProduction ? [] : Object.keys(pkg.devDependencies))
],
plugins: [...createNodePlugins(false, false, false), bundleSizeLimit(120)]
plugins: [
...createNodePlugins(false, false, false),
!isProduction && cjsTypesPlugin(),
bundleSizeLimit(160)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bumped size limit from 120 to 160

]
})
}

Expand Down Expand Up @@ -323,4 +328,18 @@ function bundleSizeLimit(limit: number): Plugin {
}
}

function cjsTypesPlugin(): Plugin {
return {
name: 'cjs-types',
generateBundle() {
const proc = spawn('pnpm', ['build-emit-cjs-types'], {
stdio: 'inherit'
})
return new Promise((resolve) => {
proc.once('close', resolve)
})
}
}
}

// #endregion
96 changes: 96 additions & 0 deletions packages/vite/scripts/emitCjsTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import fs from 'node:fs'
import path from 'node:path'
import glob from 'fast-glob'
import * as lexer from 'es-module-lexer'
import colors from 'picocolors'

async function main() {
const typeFiles = await glob('**/*.d.ts', {
cwd: 'dist',
absolute: true
})

for (const file of typeFiles) {
let text = fs.readFileSync(file, 'utf8')

const [imports] = lexer.parse(text)
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) || id.endsWith('.cjs')) {
continue
}

const importedFile = path.resolve(path.dirname(file), id)
if (isDirectory(importedFile)) {
id += '/index'
}

const cjsModuleSpec = id + '.cjs'
text = text.slice(0, i.s) + cjsModuleSpec + text.slice(i.e)
Comment on lines +33 to +34
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this adds .cjs to all file imports, do we need to do the same for node/index.d.ts to with .js only. I've seen this need in the past with node16, but i've also heard that it's not exactly needed.

I also wonder if adding .js is enough to get CJS support? so we avoid another file.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've tested explicit .js in node/index.d.ts before taking this route. It doesn't work, unfortunately.

}

const outFile = file
.replace('/node/', '/node-cjs/')
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose we should relativize file before doing this replacement

.replace(/\.ts$/, '.cts')

fs.mkdirSync(path.dirname(outFile), { recursive: true })
fs.writeFileSync(outFile, text)
}

console.log(colors.green(colors.bold(`emitted CJS types`)))
}

function isDirectory(file: string) {
try {
return fs.statSync(file).isDirectory()
} catch (e) {
return false
}
}

// 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()