-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
270 lines (233 loc) · 9.54 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import path from 'node:path'
import fs from 'node:fs/promises'
import { createRequire, isBuiltin } from 'node:module'
import type { Plugin } from 'rollup'
type MaybeFalsy<T> = (T) | undefined | null | false
type MaybeArray<T> = (T) | (T)[]
interface ViteCompatiblePlugin extends Plugin {
enforce: 'pre' | 'post'
}
export interface ExternalsOptions {
/**
* Mark node built-in modules like `path`, `fs`... as external.
*
* Defaults to `true`.
*/
builtins?: boolean
/**
* node: prefix handing for importing Node builtins:
* - `'add'` turns `'path'` to `'node:path'`
* - `'strip'` turns `'node:path'` to `'path'`
* - `'ignore'` leaves Node builtin names as-is
*
* Defaults to `add`.
*/
builtinsPrefix?: 'add' | 'strip' | 'ignore'
/**
* Path/to/your/package.json file (or array of paths).
*
* Defaults to all package.json files found in parent directories recursively.
* Won't go outside of a git repository.
*/
packagePath?: string | string[]
/**
* Mark dependencies as external.
*
* Defaults to `true`.
*/
deps?: boolean
/**
* Mark devDependencies as external.
*
* Defaults to `false`.
*/
devDeps?: boolean
/**
* Mark peerDependencies as external.
*
* Defaults to `true`.
*/
peerDeps?: boolean
/**
* Mark optionalDependencies as external.
*
* Defaults to `true`.
*/
optDeps?: boolean
/**
* Force include these deps in the list of externals, regardless of other settings.
*
* Defaults to `[]` (force include nothing).
*/
include?: MaybeArray<MaybeFalsy<string | RegExp>>
/**
* Force exclude these deps from the list of externals, regardless of other settings.
*
* Defaults to `[]` (force exclude nothing).
*/
exclude?: MaybeArray<MaybeFalsy<string | RegExp>>
}
// Fields of interest in package.json
interface PackageJson {
name: string
version: string
workspaces?: string[]
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
peerDependencies?: Record<string, string>
optionalDependencies?: Record<string, string>
}
// Get our own name and version
const { name, version } = createRequire(import.meta.url)('#package.json') as PackageJson
// Files that mark the root of a monorepo
const workspaceRootFiles = new Set([
'pnpm-workspace.yaml', // pnpm
'lerna.json', // Lerna
// Note: is there any interest in the following?
// 'workspace.jsonc', // Bit
// 'nx.json', // Nx
// 'rush.json', // Rush
])
// Our defaults.
type Config = Required<ExternalsOptions>
const defaults: Config = {
builtins: true,
builtinsPrefix: 'add',
packagePath: [],
deps: true,
devDeps: false,
peerDeps: true,
optDeps: true,
include: [],
exclude: []
}
const isString = (str: unknown): str is string =>
typeof str === 'string' && str.length > 0
/**
* A Rollup/Vite plugin that automatically declares NodeJS built-in modules,
* and optionally npm dependencies, as 'external'.
*/
function nodeExternals(options: ExternalsOptions = {}): Plugin {
const config: Config = { ...defaults, ...options }
let include: RegExp[] = [], // Initialized to empty arrays as a workaround
exclude: RegExp[] = [] // to https://github.com/Septh/rollup-plugin-node-externals/issues/30
const isIncluded = (id: string) => include.length > 0 && include.some(rx => rx.test(id)),
isExcluded = (id: string) => exclude.length > 0 && exclude.some(rx => rx.test(id))
return {
name: name.replace(/^rollup-plugin-/, ''),
version,
enforce: 'pre',
async buildStart() {
// Map the include and exclude options to arrays of regexes.
[ include, exclude ] = ([ 'include', 'exclude' ] as const).map(option => ([] as Array<MaybeFalsy<string | RegExp>>)
.concat(config[option])
.reduce((result, entry, index) => {
if (entry instanceof RegExp)
result.push(entry)
else if (isString(entry))
result.push(new RegExp('^' + entry.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$'))
else if (entry)
this.warn(`Ignoring wrong entry type #${index} in '${option}' option: ${JSON.stringify(entry)}`)
return result
}, [] as RegExp[])
)
// Populate the packagePath option if not given by getting all package.json files
// from cwd up to the root of the git repo, the root of the monorepo,
// or the root of the volume, whichever comes first.
const packagePaths = ([] as string[])
.concat(config.packagePath)
.filter(isString)
.map(packagePath => path.resolve(packagePath))
if (packagePaths.length === 0) {
for (
let current = process.cwd(), previous: string | undefined = undefined;
previous !== current;
previous = current, current = path.dirname(current)
) {
const entries = await fs.readdir(current, { withFileTypes: true }).catch(({ code }: NodeJS.ErrnoException) => code)
if (isString(entries) || !entries) {
return this.error({
message: `Could not read directory ${JSON.stringify(current)}, error: ${entries || 'UNKNOWN'}.`,
stack: undefined
})
}
// Gather package.json files.
if (entries.some(entry => entry.name === 'package.json' && entry.isFile()))
packagePaths.push(path.join(current, 'package.json'))
// Break early if this is a git repo root or there is a known workspace root file.
if (entries.some(entry =>
(entry.name === '.git' && entry.isDirectory()) || (workspaceRootFiles.has(entry.name) && entry.isFile())
)) {
break
}
}
}
// Gather dependencies names.
const dependencies: Record<string, string> = {}
for (const packagePath of packagePaths) {
const buffer = await fs.readFile(packagePath).catch(({ code }: NodeJS.ErrnoException) => code)
if (isString(buffer) || !buffer) {
return this.error({
message: `Cannot read file ${JSON.stringify(packagePath)}, error: ${buffer || 'UNKNOWN'}.`,
stack: undefined
})
}
try {
const pkg = JSON.parse(buffer.toString()) as PackageJson
Object.assign(dependencies,
config.deps ? pkg.dependencies : undefined,
config.devDeps ? pkg.devDependencies : undefined,
config.peerDeps ? pkg.peerDependencies : undefined,
config.optDeps ? pkg.optionalDependencies : undefined
)
// Watch this package.json
this.addWatchFile(packagePath)
// Break early if this is an npm/yarn workspace root.
if (Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0)
break
}
catch {
this.error({
message: `File ${JSON.stringify(packagePath)} does not look like a valid package.json file.`,
stack: undefined
})
}
}
// Add all dependencies as an include RegEx.
const names = Object.keys(dependencies)
if (names.length > 0)
include.push(new RegExp('^(?:' + names.join('|') + ')(?:/.+)?$'))
},
resolveId: {
order: 'pre',
async handler(specifier, importer, { isEntry }) {
if (
isEntry // Ignore entry points (they should always be resolved)
|| /^(?:\0|\.{1,2}\/)/.test(specifier) // Ignore virtual modules and relative imports
|| path.isAbsolute(specifier) // Ignore already resolved ids
) {
return null
}
// Handle node builtins.
if (isBuiltin(specifier)) {
const stripped = specifier.replace(/^node:/, '')
return {
id: config.builtinsPrefix === 'ignore'
? specifier
: config.builtinsPrefix === 'add' || !isBuiltin(stripped)
? 'node:' + stripped
: stripped,
external: (config.builtins || isIncluded(specifier)) && !isExcluded(specifier),
moduleSideEffects: false
}
}
// Handle npm dependencies.
return isIncluded(specifier) && !isExcluded(specifier)
? false // external
: null // normal handling
}
}
} as ViteCompatiblePlugin
}
export default nodeExternals
export { nodeExternals }