Skip to content

Commit b2e46b5

Browse files
committed
Externalize Node builtin modules
1 parent 5ac0fdf commit b2e46b5

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { existsSync, readFileSync } from 'node:fs'
2+
import { builtinModules } from 'node:module'
23
import { join } from 'node:path'
34
import type { Plugin } from 'vite'
45

56
interface UserOptions {
67
deps: boolean,
8+
nodeBuiltins: boolean,
79
optionalDeps: boolean,
810
peerDeps: boolean,
911
useFile: string,
@@ -16,6 +18,7 @@ const parseFile = (file: string) => {
1618
export const externalizeDeps = (options: Partial<UserOptions> = {}): Plugin => {
1719
const optionsResolved: UserOptions = {
1820
deps: true,
21+
nodeBuiltins: true,
1922
optionalDeps: true,
2023
peerDeps: true,
2124
useFile: join(process.cwd(), 'package.json'),
@@ -38,6 +41,14 @@ export const externalizeDeps = (options: Partial<UserOptions> = {}): Plugin => {
3841
})
3942
}
4043

44+
if (optionsResolved.nodeBuiltins) {
45+
builtinModules.forEach((builtinModule) => {
46+
const builtinMatcher = new RegExp(`^(?:node:)?${builtinModule}$`)
47+
48+
externalDeps.add(builtinMatcher)
49+
})
50+
}
51+
4152
if (optionsResolved.optionalDeps) {
4253
Object.keys(optionalDependencies).forEach((dep) => {
4354
const depMatcher = new RegExp(`^${dep}(?:/.+)?$`)

test/entry.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import path from 'path'
2+
import path2 from 'node:path'
3+
import { resolve } from 'path'
14
import chalk from 'chalk'
25

3-
console.log(chalk.green('hello'))
6+
console.log(path, path2, resolve, chalk)

0 commit comments

Comments
 (0)