@@ -6,6 +6,7 @@ import type { Plugin } from 'vite'
6
6
interface UserOptions {
7
7
deps : boolean ,
8
8
devDeps : boolean ,
9
+ except : Array < string | RegExp > ,
9
10
nodeBuiltins : boolean ,
10
11
optionalDeps : boolean ,
11
12
peerDeps : boolean ,
@@ -16,10 +17,41 @@ const parseFile = (file: string) => {
16
17
return JSON . parse ( readFileSync ( file ) . toString ( ) )
17
18
}
18
19
20
+ /**
21
+ * Returns a Vite plugin to exclude dependencies from the bundle.
22
+ *
23
+ * @example
24
+ *
25
+ * ```ts
26
+ * // vite.config.ts
27
+ * import { defineConfig } from 'vite'
28
+ * import { externalizeDeps } from 'vite-plugin-externalize-deps'
29
+ *
30
+ * export default defineConfig({
31
+ * plugins: [
32
+ * externalizeDeps({
33
+ * deps: true,
34
+ * devDeps: false,
35
+ * except: [
36
+ * // Match exact values with strings.
37
+ * '@some /obscure/dependency',
38
+ * // Or match patterns with regular expressions.
39
+ * /^@some\/obscure(?:\/.+)?$/,
40
+ * ],
41
+ * nodeBuiltins: true,
42
+ * optionalDeps: true,
43
+ * peerDeps: true,
44
+ * useFile: join(process.cwd(), 'package.json'),
45
+ * }),
46
+ * ],
47
+ * })
48
+ * ```
49
+ */
19
50
export const externalizeDeps = ( options : Partial < UserOptions > = { } ) : Plugin => {
20
51
const optionsResolved : UserOptions = {
21
52
deps : true ,
22
53
devDeps : false ,
54
+ except : [ ] ,
23
55
nodeBuiltins : true ,
24
56
optionalDeps : true ,
25
57
peerDeps : true ,
@@ -83,12 +115,27 @@ export const externalizeDeps = (options: Partial<UserOptions> = {}): Plugin => {
83
115
} )
84
116
}
85
117
118
+ const depMatchers = Array . from ( externalDeps )
119
+ const isException = ( id : string ) => {
120
+ return optionsResolved . except . some ( ( exception ) => {
121
+ if ( typeof exception === 'string' ) {
122
+ return exception === id
123
+ }
124
+
125
+ return exception . test ( id )
126
+ } )
127
+ }
128
+
86
129
return {
87
130
build : {
88
131
rollupOptions : {
89
- external : [
90
- ...externalDeps . values ( ) ,
91
- ] ,
132
+ external : ( id ) => {
133
+ if ( isException ( id ) ) {
134
+ return false
135
+ }
136
+
137
+ return depMatchers . some ( ( depMatcher ) => depMatcher . test ( id ) )
138
+ } ,
92
139
} ,
93
140
} ,
94
141
}
0 commit comments