-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This will allow CJS projects using "moduleResolution: node16" to import Vite.
- Loading branch information
1 parent
18c71dc
commit c9c53cf
Showing
3 changed files
with
47 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './dist/node-cjs/index.cjs' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import fs from 'node:fs' | ||
import path from 'node:path' | ||
import glob from 'fast-glob' | ||
import * as lexer from 'es-module-lexer' | ||
|
||
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) | ||
for (const i of [...imports].reverse()) { | ||
let id = i.n | ||
if (!id || !/^\.\.?(?:\/|$)/.test(id)) { | ||
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) | ||
} | ||
const outFile = file | ||
.replace('/node/', '/node-cjs/') | ||
.replace(/\.ts$/, '.cts') | ||
fs.mkdirSync(path.dirname(outFile), { recursive: true }) | ||
fs.writeFileSync(outFile, text) | ||
console.log('saved', outFile) | ||
} | ||
} | ||
|
||
function isDirectory(file: string) { | ||
try { | ||
return fs.statSync(file).isDirectory() | ||
} catch (e) { | ||
return false | ||
} | ||
} | ||
|
||
main() |