-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathrollup.config.js
397 lines (383 loc) · 11.4 KB
/
rollup.config.js
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// @ts-check
import fs from 'fs'
import path from 'path'
import nodeResolve from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import alias from '@rollup/plugin-alias'
import license from 'rollup-plugin-license'
import MagicString from 'magic-string'
import colors from 'picocolors'
import fg from 'fast-glob'
import { sync as resolve } from 'resolve'
/**
* @type { import('rollup').RollupOptions }
*/
const envConfig = {
input: path.resolve(__dirname, 'src/client/env.ts'),
plugins: [
typescript({
target: 'es2018',
include: ['src/client/env.ts'],
baseUrl: path.resolve(__dirname, 'src/env'),
paths: {
'types/*': ['../../types/*']
}
})
],
output: {
file: path.resolve(__dirname, 'dist/client', 'env.mjs'),
sourcemap: true
}
}
/**
* @type { import('rollup').RollupOptions }
*/
const clientConfig = {
input: path.resolve(__dirname, 'src/client/client.ts'),
external: ['./env', '@vite/env'],
plugins: [
typescript({
target: 'es2018',
include: ['src/client/**/*.ts'],
baseUrl: path.resolve(__dirname, 'src/client'),
paths: {
'types/*': ['../../types/*']
}
})
],
output: {
file: path.resolve(__dirname, 'dist/client', 'client.mjs'),
sourcemap: true
}
}
/**
* @type { import('rollup').RollupOptions }
*/
const sharedNodeOptions = {
treeshake: {
moduleSideEffects: 'no-external',
propertyReadSideEffects: false,
tryCatchDeoptimization: false
},
output: {
dir: path.resolve(__dirname, 'dist'),
entryFileNames: `node/[name].js`,
chunkFileNames: 'node/chunks/dep-[hash].js',
exports: 'named',
format: 'cjs',
externalLiveBindings: false,
freeze: false
},
onwarn(warning, warn) {
// node-resolve complains a lot about this but seems to still work?
if (warning.message.includes('Package subpath')) {
return
}
// we use the eval('require') trick to deal with optional deps
if (warning.message.includes('Use of eval')) {
return
}
if (warning.message.includes('Circular dependency')) {
return
}
warn(warning)
}
}
/**
*
* @param {boolean} isProduction
* @returns {import('rollup').RollupOptions}
*/
const createNodeConfig = (isProduction) => {
/**
* @type { import('rollup').RollupOptions }
*/
const nodeConfig = {
...sharedNodeOptions,
input: {
index: path.resolve(__dirname, 'src/node/index.ts'),
cli: path.resolve(__dirname, 'src/node/cli.ts')
},
output: {
...sharedNodeOptions.output,
sourcemap: !isProduction
},
external: [
'fsevents',
...Object.keys(require('./package.json').dependencies),
...(isProduction
? []
: Object.keys(require('./package.json').devDependencies))
],
plugins: [
alias({
// packages with "module" field that doesn't play well with cjs bundles
entries: {
'@vue/compiler-dom': require.resolve(
'@vue/compiler-dom/dist/compiler-dom.cjs.js'
)
}
}),
nodeResolve({ preferBuiltins: true }),
typescript({
tsconfig: 'src/node/tsconfig.json',
module: 'esnext',
target: 'es2019',
include: ['src/**/*.ts', 'types/**'],
exclude: ['src/**/__tests__/**'],
esModuleInterop: true,
// in production we use api-extractor for dts generation
// in development we need to rely on the rollup ts plugin
...(isProduction
? {
declaration: false,
sourceMap: false
}
: {
declaration: true,
declarationDir: path.resolve(__dirname, 'dist/node')
})
}),
// Some deps have try...catch require of optional deps, but rollup will
// generate code that force require them upfront for side effects.
// Shim them with eval() so rollup can skip these calls.
isProduction &&
shimDepsPlugin({
'plugins/terser.ts': {
src: `require.resolve('terser'`,
replacement: `require.resolve('vite/dist/node/terser'`
},
// chokidar -> fsevents
'fsevents-handler.js': {
src: `require('fsevents')`,
replacement: `eval('require')('fsevents')`
},
// cac re-assigns module.exports even in its mjs dist
'cac/dist/index.mjs': {
src: `if (typeof module !== "undefined") {`,
replacement: `if (false) {`
},
// postcss-import -> sugarss
'process-content.js': {
src: 'require("sugarss")',
replacement: `eval('require')('sugarss')`
},
'lilconfig/dist/index.js': {
pattern: /: require,/g,
replacement: `: eval('require'),`
},
// postcss-load-config calls require after register ts-node
'postcss-load-config/src/index.js': {
src: `require(configFile)`,
replacement: `eval('require')(configFile)`
}
}),
commonjs({
extensions: ['.js'],
// Optional peer deps of ws. Native deps that are mostly for performance.
// Since ws is not that perf critical for us, just ignore these deps.
ignore: ['bufferutil', 'utf-8-validate']
}),
json(),
isProduction && licensePlugin()
]
}
return nodeConfig
}
/**
* Terser needs to be run inside a worker, so it cannot be part of the main
* bundle. We produce a separate bundle for it and shims plugin/terser.ts to
* use the production path during build.
*
* @type { import('rollup').RollupOptions }
*/
const terserConfig = {
...sharedNodeOptions,
output: {
...sharedNodeOptions.output,
exports: 'default',
sourcemap: false
},
input: {
terser: require.resolve('terser')
},
plugins: [nodeResolve(), commonjs()]
}
/**
* @type { (deps: Record<string, { src?: string, replacement: string, pattern?: RegExp }>) => import('rollup').Plugin }
*/
function shimDepsPlugin(deps) {
const transformed = {}
return {
name: 'shim-deps',
transform(code, id) {
for (const file in deps) {
if (id.replace(/\\/g, '/').endsWith(file)) {
const { src, replacement, pattern } = deps[file]
const magicString = new MagicString(code)
if (src) {
const pos = code.indexOf(src)
if (pos < 0) {
this.error(
`Could not find expected src "${src}" in file "${file}"`
)
}
transformed[file] = true
magicString.overwrite(pos, pos + src.length, replacement)
console.log(`shimmed: ${file}`)
}
if (pattern) {
let match
while ((match = pattern.exec(code))) {
transformed[file] = true
const start = match.index
const end = start + match[0].length
magicString.overwrite(start, end, replacement)
}
if (!transformed[file]) {
this.error(
`Could not find expected pattern "${pattern}" in file "${file}"`
)
}
console.log(`shimmed: ${file}`)
}
return {
code: magicString.toString(),
map: magicString.generateMap({ hires: true })
}
}
}
},
buildEnd(err) {
if (!err) {
for (const file in deps) {
if (!transformed[file]) {
this.error(
`Did not find "${file}" which is supposed to be shimmed, was the file renamed?`
)
}
}
}
}
}
}
function licensePlugin() {
return license({
thirdParty(dependencies) {
// https://github.com/rollup/rollup/blob/master/build-plugins/generate-license-file.js
// MIT Licensed https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md
const coreLicense = fs.readFileSync(
path.resolve(__dirname, '../../LICENSE')
)
function sortLicenses(licenses) {
let withParenthesis = []
let noParenthesis = []
licenses.forEach((license) => {
if (/^\(/.test(license)) {
withParenthesis.push(license)
} else {
noParenthesis.push(license)
}
})
withParenthesis = withParenthesis.sort()
noParenthesis = noParenthesis.sort()
return [...noParenthesis, ...withParenthesis]
}
const licenses = new Set()
const dependencyLicenseTexts = dependencies
.sort(({ name: nameA }, { name: nameB }) =>
nameA > nameB ? 1 : nameB > nameA ? -1 : 0
)
.map(
({
name,
license,
licenseText,
author,
maintainers,
contributors,
repository
}) => {
let text = `## ${name}\n`
if (license) {
text += `License: ${license}\n`
}
const names = new Set()
if (author && author.name) {
names.add(author.name)
}
for (const person of maintainers.concat(contributors)) {
if (person && person.name) {
names.add(person.name)
}
}
if (names.size > 0) {
text += `By: ${Array.from(names).join(', ')}\n`
}
if (repository) {
text += `Repository: ${repository.url || repository}\n`
}
if (!licenseText) {
try {
const pkgDir = path.dirname(
resolve(path.join(name, 'package.json'), {
preserveSymlinks: false
})
)
const licenseFile = fg.sync(`${pkgDir}/LICENSE*`, {
caseSensitiveMatch: false
})[0]
if (licenseFile) {
licenseText = fs.readFileSync(licenseFile, 'utf-8')
}
} catch {}
}
if (licenseText) {
text +=
'\n' +
licenseText
.trim()
.replace(/(\r\n|\r)/gm, '\n')
.split('\n')
.map((line) => `> ${line}`)
.join('\n') +
'\n'
}
licenses.add(license)
return text
}
)
.join('\n---------------------------------------\n\n')
const licenseText =
`# Vite core license\n` +
`Vite is released under the MIT license:\n\n` +
coreLicense +
`\n# Licenses of bundled dependencies\n` +
`The published Vite artifact additionally contains code with the following licenses:\n` +
`${sortLicenses(licenses).join(', ')}\n\n` +
`# Bundled dependencies:\n` +
dependencyLicenseTexts
const existingLicenseText = fs.readFileSync('LICENSE.md', 'utf8')
if (existingLicenseText !== licenseText) {
fs.writeFileSync('LICENSE.md', licenseText)
console.warn(
colors.yellow(
'\nLICENSE.md updated. You should commit the updated file.\n'
)
)
}
}
})
}
export default (commandLineArgs) => {
const isDev = commandLineArgs.watch
const isProduction = !isDev
return [
envConfig,
clientConfig,
createNodeConfig(isProduction),
...(isProduction ? [terserConfig] : [])
]
}